我正在研究描述符以及它们是如何在属性和函数背后使用的机制。当我们实现描述符与使用属性时,我对如何查找属性感到有点困惑。
class NonDataDescriptor(object):
def __get__(self, instance, owner):
return 'non-data descriptor'
class DataDescriptor(object):
def __get__(self, instance, owner):
return 'data descriptor'
def __set__(self, instance, value):
pass
class MyClass(object):
descriptor_one = NonDataDescriptor()
descriptor_two = DataDescriptor()
def __init__(self):
self.descriptor_one = 'hello'
self.descriptor_two = 'goodbye'
mc = MyClass()
print(mc.descriptor_one)
print(mc.descriptor_two)
输出是:
hello
data descriptor
这是有道理的,因为属性查找顺序是:
- 数据描述符
instance_obj.__dict__中的实例属性- 非数据描述符
由于属性实际上只是实现描述符,我想知道为什么这种属性查找顺序似乎没有得到遵守。请参阅以下内容:
class MyClass(object):
def __init__(self, fname, lname):
self._fname = fname
self._lname = lname
@property
def fullname(self):
return '{} {}'.format(self._fname, self._lname)
mc = MyClass('Bob', 'John')
print(mc.fullname)
mc.__dict__['fullname'] = 'testing'
print(mc.__dict__)
print(mc.fullname)
输出是:
Bob John
{'_fname': 'Bob', '_lname': 'John', 'fullname': 'testing'}
Bob John
我原以为属性对象 fullname 实际上只是一个非数据描述符,所以实例属性 fullname 会优先。
此外,函数也被实现为非数据描述符,并且遵循这种属性查找顺序:
class Test:
def __init__(self):
self.display = 'display instance attribute'
def display(self):
print('display from instance method')
t = Test()
print(t.display)
输出是:
display instance attribute
谁能解释为什么它与属性对象不同?
请您参考如下方法:
诀窍在于 descriptor protocol这里:
- If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence.
- If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.
@property
def fullname(self):
return '{} {}'.format(self._fname, self._lname)
这是一个数据描述符,因为装饰器返回的property对象总是定义了__set__,即使你没有定义setter(那么__set__ 将引发一个 AttributeError,请参阅 code here)。
>>> MyClass.fullname
<property object at 0x7f30e3917958>
>>> MyClass.fullname.__set__
<method-wrapper '__set__' of property object at 0x7f30e3917958>
因此,数据描述符优先。
由于其他示例的行为已经符合您的预期,这应该足以完成您的理解。
