如何覆盖python中的类属性访问?


问题内容

如何覆盖python中的类属性访问?

PS是否有一种方法可以不对类属性进行常规访问,而是对缺少的属性调用更具体的异常?


问题答案:

__getattr__当属性不上实例/类/父类存在魔术方法被调用。您将使用它为缺少的属性引发特殊异常:

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

如果要自定义对类属性的访问,则需要__getattr__在元类/类型上进行定义:

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

如果要自定义 所有
属性访问,请使用__getattribute__magic方法。