Python中非数据描述符和实例条目之间的优先级

时间:2017-10-09 21:42:30

标签: python python-3.x descriptor

在Python 3.6文档的“Descriptor HowTo Guide"的“描述符协议”段落中写了

  

如果实例的字典有一个与a同名的条目   非数据描述符,字典条目优先

也许我理解错误,但为什么非数据描述符优先于此示例中的实例条目

class Descriptor:
    def __get__( self, instance, owner ):
        print( "__get__ is called" )
        return self.__dict__[self.name]


    def __set_name__( self, owner, name ):
        print( "__set_name__ is called" )
        self.name = name
        self.__dict__[name] = "Hello World"

d = Descriptor()

class MyClass:
    data = d

instance_of = MyClass()
instance_of.d = "Goodbye"

print()
print( instance_of.data )

我预计会输出Goodbye。但是输出了Hello World

1 个答案:

答案 0 :(得分:0)

这不是“名字”的意思。这里的“名称”是指类__dict__和实例__dict__中的名称,而不是描述符可能具有的任何名称属性。有关何时覆盖类描述符,请参阅以下示例。

from pprint import pprint

class Descriptor:
    def __get__( self, instance, owner ):
        return "class"

class MyClass:
    data = Descriptor()

obj = MyClass()
# get the data descriptor's value
print(obj.data) # prints "class"

# set an instance attribute with the same name
obj.data = "instance"
print(obj.data) # prints "instance"

# print the variables of both class and instance
# -- both contain the name "data"
pprint(vars(MyClass)) # prints
# mappingproxy({'__dict__': <attribute '__dict__' of 'MyClass' objects>,
#               '__doc__': None,
#               '__module__': '__main__',
#               '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
#               'data': <__main__.Descriptor object at 0x034BF1B0>})
print(vars(obj)) # prints
# {'data': 'instance'}

# delete the instance attribute and the descriptor becomes visible again
del obj.data
print(obj.data) # prints "class" again