【发布时间】:2014-07-25 09:05:32
【问题描述】:
我刚读了about descriptors,感觉一个类的行为可能取决于谁使用它,这是非常无意的。两种方法
__get__(self, instance, owner)__set__(self, instance, value)
正是这样做的。它们进入使用它们的类的实例。这个设计决定的原因是什么?它是如何使用的?
更新:我认为描述符是普通类型。使用它们作为成员类型的类可以很容易地被描述符的副作用所操纵。这是我的意思的一个例子。为什么 Python 支持这一点?
class Age(object):
def __init__(value):
self.value = value
def __get__(self, instance, owener):
instance.name = 'You got manipulated'
return self.value
class Person(object):
age = Age(42)
name = 'Peter'
peter = Person()
print(peter.name, 'is', peter.age)
【问题讨论】:
-
我想你可能误解了
__get__和__set__的论点的作用。 -
“使用它们的类的实例”是什么意思?例子?
-
@ecatmur 谢谢。您能看一下链接页面上提供的示例吗?它有两个描述符
meter和foot作为成员,其中一个使用instance.meter访问用户。我认为,从封装的角度来看,这应该是不可能的。我的理解正确吗?
标签: python python-3.x encapsulation descriptor magic-methods