python – 覆盖-Class Attribute- getter
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 覆盖-Class Attribute- getter,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2571字,纯文字阅读大概需要4分钟。
内容图文
![python – 覆盖-Class Attribute- getter](/upload/InfoBanner/zyjiaocheng/758/2e0b894e1d734e33aebaa36e1429899f.jpg)
我正在定义一个Debug类,如下所示:
_debug = False
class Debug:
DrawOutlines = True
InvinciblePlayer = True
我想覆盖Debug类,这样如果_debug为False,Debug的任何类属性(存在)都将为False.为了更改类属性的访问方式,我覆盖了什么__function__?
编辑:
我知道简单地覆盖__getattribute__将不适用于类属性:
>>> _debug = False
False
>>> class Debug:
... DrawOutlines = True
...
... def __getattribute__(self, name):
... return _debug and object.__getattribute__(self, name)
...
>>> Debug.DrawOutlines
True
>>> Debug.cake
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'Debug' has no attribute 'cake'
这是否需要一个元类?
解决方法:
是的,你需要一个元类,因为如果你在Debug类中定义__getattribute__(注意,必须是一个新式的类),Python将调用它来针对Debug的实例进行属性查找,而不是针对Debug本身的属性查找.
这是有道理的,因为Debug .__ getattribute__被定义为在Debug的实例上操作,而不是Debug类. (你可以想象定义一个classmethod __getattribute__,但是我找不到任何证据表明Python有任何机制会调用这样的东西.)
我在这里想到的第一件事是添加另一个__getattribute__,其中Python将为Debug类属性查找寻找它,即,在Debug类是实例的类中:Debug .__ class __.__ getattribute__.
这确实存在并按预期工作:
>>> Debug.__class__.__getattribute__(Debug, 'Draw')
True
>>> Debug.__class__.__getattribute__(Debug, 'Bogus')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __getattribute__
AttributeError: 'DebugType' object has no attribute 'Bogus'
但它不可修改:
>>> Debug.__class__.__getattribute__ = Debug.__getattribute__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'type'
这似乎只是Python实现的一个事实;虽然存在这个概念,但是不允许修改内置类型的属性,因此这种方法不起作用.
但是,metaclasses来救援.你可能已经知道如何做到这一点,但对于其他读者我会给出一个例子(在this answer还有另一个例子,我的答案欠了一些债务).
_debug = True
>>> class DebugType(type):
... def __getattribute__(self, name):
... print 'attr lookup for %s' % str(name)
... return _debug and object.__getattribute__(self, name)
...
>>> class Debug(object):
... Draw = True
... __metaclass__ = DebugType
...
>>> _debug
False
>>> Debug.Draw
attr lookup for Draw
False
>>> _debug = True
>>> Debug.Draw
attr lookup for Draw
True
因此,为了简化它,类的默认类实现是类型,因此类属性的默认属性looker-upper是类型.__ getattribute__,并且您不能直接修改或替换类型.__ getattribute__,但是您可以使用元类机制替换类型,并且,如上例所示,将其替换为具有所需__getattribute__的类型的子类.
内容总结
以上是互联网集市为您收集整理的python – 覆盖-Class Attribute- getter全部内容,希望文章能够帮你解决python – 覆盖-Class Attribute- getter所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。