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方法.