問題描述
如何在 python 中覆蓋類屬性訪問?
How can I override class attribute access in python?
附:有沒有辦法單獨保留對類屬性的常規(guī)訪問,但在缺少屬性時調用更具體的異常?
P.S. Is there a way to leave regular access to class attributes alone but calling a more specific exception on missing attribute?
推薦答案
__getattr__
屬性在實例/類/父類上不存在時調用魔術方法.您可以使用它為缺少的屬性引發(fā)特殊異常:
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 when 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
如果您想自定義 all 屬性訪問,請使用 __getattribute__
魔術方法.
If you want to customize all attribute access, use the __getattribute__
magic method.
這篇關于如何在 python 中覆蓋類屬性訪問?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!