有人可以通过示例帮助我理解这一点吗?
如果实例的字典中有一个条目与数据描述符同名,则数据描述符优先。如果一个实例的字典有一个与非数据描述符同名的条目,则该字典条目优先。
该实现通过优先链工作,该优先链使数据描述符优先于实例变量,实例变量优先于非数据描述符,并将最低优先级分配给 _ getattr_()(如果提供)。
具体我不明白的是:
一个实例的字典怎么会有一个与描述符同名的条目。能举个例子吗?
您还可以给我一个例子,其中数据描述符优先于实例变量,实例变量优先于非数据描述符等吗?
同样在下面的代码中,我惊讶地看到测试类中的 self.x 调用了 __ set __: 我相信这种行为是因为上面链接中的解释:
对于对象,机制在 object.__ getattribute __ () 中,它将 b.x 转换为 type(b)。 __ 字典 __ ['x']。 __ 得到 __(b,类型(b))。对吧??
#! /usr/bin/env python
class descclass(object):
def __init__(self, value):
print "in desc init"
self.value = value
print "out of desc init"
def __get__(self, inst, insttype):
print "in desc get"
return self.value
def __set__(self,inst, val):
print "in desc set"
self.value = val
class testclass(object):
x = descclass(100)
print "desc created"
def __init__(self, val):
print "in testclass init"
self.x = val # this invokes __set__ on descriptor in x
print "out of testclass init"
if __name__ == '__main__':
t = testclass(45)
print t.x
print vars(t)
print vars(testclass)
最佳答案
这是一个例子。
# Not a data descriptor because it doesn't define __set__
class NonDataDescriptor(object):
def __get__(self, obj, objtype):
return 3
class Namespace(object):
# Data descriptor - defines both __get__ and __set__
@property
def foo(self):
return 3
bar = NonDataDescriptor()
x = Namespace()
x.__dict__['foo'] = 4 # We bypass the foo descriptor's __set__ here,
x.bar = 4 # but there's no bar setter, so this one goes to the dict
# x now has foo and bar descriptors and __dict__ entries
print x.foo # prints 3 - data descriptor wins over instance __dict__ entry
print x.bar # prints 4 - instance __dict__ entry wins over non-data descriptor
关于python - 关于 python 描述符的几个说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18368019/