Which Python language rule allows the descriptor to be found first?

不羁的心 提交于 2019-12-11 01:59:23

问题


I bumped into the following last night and I'm still at a loss as to explain it:

class Foo(object):
    @property
    def dave(self):
        vars(self)['dave'] = 1
        return 2

f = Foo()
print f.dave
print f.dave

Running this code produces:

2
2

The question is why? My understanding of attribute access is that the instance dictionary is checked before the class dictionary, and the dictionary of any bases, however as seen above the instance dictionary doesn't appear to be getting checked before the descriptor is found in the class dictionary.


回答1:


My understanding of attribute access is that the instance dictionary is checked before the class dictionary, and the dictionary of any bases

Data descriptors are an exception:

For instance bindings, the precedence of descriptor invocation depends on the which descriptor methods are defined. Normally, data descriptors define both __get__() and __set__(), while non-data descriptors have just the __get__() method. Data descriptors always override a redefinition in an instance dictionary. In contrast, non-data descriptors can be overridden by instances.

http://docs.python.org/reference/datamodel.html#invoking-descriptors



来源:https://stackoverflow.com/questions/1865902/which-python-language-rule-allows-the-descriptor-to-be-found-first

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!