哪个 Python 语言规则允许首先找到描述符? [英] Which Python language rule allows the descriptor to be found first?

查看:35
本文介绍了哪个 Python 语言规则允许首先找到描述符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨晚我遇到了以下问题,但我仍然无法解释:

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

运行此代码会产生:

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.

推荐答案

我对属性访问的理解是先检查实例字典,再检查类字典,任意基的字典

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:

对于实例绑定,描述符调用的优先级取决于定义了哪些描述符方法.通常,数据描述符同时定义了 __get__()__set__(),而非数据描述符只有 __get__() 方法.数据描述符总是覆盖实例字典中的重新定义.相反,非数据描述符可以被实例覆盖.

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

这篇关于哪个 Python 语言规则允许首先找到描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆