我如何可以覆盖Python类属性的访问? [英] How can I override class attribute access in python?

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

问题描述

我如何可以覆盖Python类属性的访问?

How can I override class attribute access in python?

P.S。有没有办法留下来上课经常接触单独的属性,但呼吁缺少的属性更具体的例外?

P.S. Is there a way to leave regular access to class attributes alone but calling a more specific exception on missing attribute?

推荐答案

的<一个href=\"http://docs.python.org/dev/reference/datamodel.html#object.__getattr__\"><$c$c>__getattr__当属性不上实例/类/父类存在魔术方法被调用。你会用它来提高一个特殊的例外缺少的属性:

The __getattr__ magic method is called when the attribute doesn't exist on the instance / class / parent classes. You'd use it to raise a special exception for a missing attribute:

class Foo(object):
    def __getattr__(self, attr):
        #only called what self.attr doesn't exist
        raise MyCustonException(attr)

如果你想定制访问类的属性,您需要定义 __ __ GETATTR 在元类/类型:

If you want to customize access to class attributes, you need to define __getattr__ on the metaclass / type:

class BooType(type):
    def __getattr__(self, attr):
        print attr
        return attr

class Boo(object):
    __metaclass__ = BooType

boo = Boo()
Boo.asd # prints asd
boo.asd # raises an AttributeError like normal

如果您想自定义的所有的属性的访问,使用<$c$c>__getattribute__魔术方法。

If you want to customize all attribute access, use the __getattribute__ magic method.

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

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