Python 实例变量的优先级高于数据描述符?
医生,有一个优先的结论Python 实例变量的优先级高于数据描述符?,python,Python,医生,有一个优先的结论 The implementation works through a precedence chain that gives data descriptors priority over instance variables, instance variables priority over non-data descriptors, and assigns lowest priority to __getattr__() if provided.
The implementation works through a precedence chain that gives data descriptors priority over
instance variables, instance variables priority over non-data descriptors, and assigns lowest
priority to __getattr__() if provided.
但当我尝试我的审判如下:
class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print('Retrieving', self.name)
return self.val
def __set__(self, obj, val):
print('Updating' , self.name)
self.val = val
class MyClass(object):
x = RevealAccess(10, 'x')
m = MyClass()
m.x = 1
print(m.__dict__) # {}
print(MyClass.__dict__) # {'__module__': '__main__', 'x': <__main__.RevealAccess object at 0x0000018EB4C6D908>, 'y': 5, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
print(m.x) # 1 why this value is not 10 here
print(m.__dict__)
class RevealAccess(对象):
“”“设置和返回值的数据描述符
正常情况下,会打印一条记录其访问权限的消息。
"""
def uuu init uuu(self,initval=None,name='var'):
self.val=initval
self.name=名称
定义获取(self、obj、objtype):
打印('正在检索',self.name)
返回self.val
定义设置(自身、对象、值):
打印('更新',self.name)
self.val=val
类MyClass(对象):
x=RevealAccess(10,'x')
m=MyClass()
m、 x=1
印刷体(印刷体)
打印(MyClass.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
打印(m.x)#1为什么这里的值不是10
打印(m.u_udict_u_u)
为什么在数据描述符中将该值设置为10后该值仍然为1?该值为1,因为您将其设置为1。10只是初始值 描述符的
\uuuuu init\uuuuuu
将self.val
设置为10
(其中self
是描述符),但随后在m.x=1
上触发self.val
并将self.val
设置为1
。然后,您的\uu获取
返回self.val
,现在是1
没有任何内容比数据描述符具有接收优先级。数据描述符始终处理该属性