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

Rom*_*her 9 python attributes

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

PS有没有办法单独保留对类属性的常规访问权限,但是在缺少属性时调用更具体的异常?

agf*_*agf 17

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

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

如果要自定义对类属性的访问,则需要__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
Run Code Online (Sandbox Code Playgroud)

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

  • 这不是修改实例而不是类属性访问吗? (2认同)