为什么要 __getattribute__ 引发 AttributeError 异常?
Why should __getattribute__ raise an AttributeError exception?
__getattribute__
方法的文档指出:
This method should return the (computed) attribute value or raise an
AttributeError
exception.
如果我在此方法中引发自定义异常而不是 AttributeError
,是否会出现问题?
原因实际上就在您链接的文档上方,__getattr__
取决于引发的 AttributeError 是否正常工作。来自 __getattr__
的文档:
Called when the default attribute access fails with an AttributeError (either __getattribute__()
raises an AttributeError
because name is not an instance attribute or an attribute in the class tree for self; [...]
回答原始问题:您应该提出一个 AttributeError
或一个继承自 AttributeError
的自定义异常。不这样做会破坏标准行为。
注意:根据您的使用情况,您可能希望改用 __getattr__
。
__getattribute__
方法的文档指出:
This method should return the (computed) attribute value or raise an
AttributeError
exception.
如果我在此方法中引发自定义异常而不是 AttributeError
,是否会出现问题?
原因实际上就在您链接的文档上方,__getattr__
取决于引发的 AttributeError 是否正常工作。来自 __getattr__
的文档:
Called when the default attribute access fails with an AttributeError (either
__getattribute__()
raises anAttributeError
because name is not an instance attribute or an attribute in the class tree for self; [...]
回答原始问题:您应该提出一个 AttributeError
或一个继承自 AttributeError
的自定义异常。不这样做会破坏标准行为。
注意:根据您的使用情况,您可能希望改用 __getattr__
。