Python:元类属性有时会覆盖类属性? [英] Python: Metaclass properties override class attributes, sometimes?

查看:81
本文介绍了Python:元类属性有时会覆盖类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码的结果使我感到困惑:

The result of the below code boggles me:

class MyClass(type):
    @property
    def a(self):
        return 1

class MyObject(object):
    __metaclass__ = MyClass

    a = 2

print MyObject.a
print object.__getattribute__(MyObject, 'a')
print type.__getattribute__(MyObject, 'a')
print MyObject.__dict__['a']
print MyObject().a

我真的希望这会重复打印2,但是它会打印1 1 1 2 2.有什么办法可以使之具有直观意义吗?

I really expect this to just print 2 repeatedly, but it prints 1 1 1 2 2. Is there a way this makes any intuitive sense?

澄清一下:我了解此行为已被详细记录(此处为数据描述符" ),但我想了解为什么这样有意义,以及核心开发者为何以这种方式实现描述符.

To clarify: I understand that this behavior is well documented (here, "data descriptors"), but I want to have an understanding of why this makes sense, and why the core devs implemented descriptors this way.

推荐答案

属性是数据描述符;在属性查找中,它们优先于具有该属性的类实例的字典中的同名条目.这意味着使用

Properties are data descriptors; in attribute lookups, they take priority over identically-named entries in the dict of an instance of the class with the property. That means that with

MyObject.a

MyClass中的a属性优先于MyObject字典中的a条目.同样,

the a property in MyClass takes priority over the a entry in MyObject's dict. Similarly,

object.__getattribute__(MyObject, 'a')
type.__getattribute__(MyObject, 'a')

object.__getattribute__type.__getattribute__都尊重数据描述符的优先级高于实例dict条目的优先级,因此属性获胜.

object.__getattribute__ and type.__getattribute__ both respect the priority of data descriptors over instance dict entries, so the property wins.

另一方面,

MyObject.__dict__['a']

这将显式执行dict查找.它只会看到MyObject的字典中的内容,而忽略了常规的属性查找机制.

this explicitly does a dict lookup. It only sees things in MyObject's dict, ignoring the normal attribute lookup mechanisms.

对于最后一行:

MyObject().a

MyClass描述符仅适用于MyClass的实例,不适用于其实例的实例.属性查找机制看不到该属性.

the MyClass descriptor only applies to instances of MyClass, not instances of its instances. The attribute lookup mechanism doesn't see the property.

这篇关于Python:元类属性有时会覆盖类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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