为什么应该引发 AttributeError 异常?

huangapple go评论74阅读模式
英文:

Why should __getattribute__ raise an AttributeError exception?

问题

此方法的文档__getattribute__中指出:

> 此方法应返回(计算的)属性值或引发AttributeError异常。

如果我在此方法中引发自定义异常而不是AttributeError,是否会出现任何问题?

英文:

The documentation on the __getattribute__ method states:

> This method should return the (computed) attribute value or raise an
> AttributeError exception.

Will anything break if I raise a custom exception instead of an AttributeError in this method?

答案1

得分: 1

原因实际上就在你提供的文档链接上方,__getattr__ 的正常运作依赖于引发 AttributeError 错误。从 __getattr__ 的文档中可以看到:

> 当默认属性访问由于 AttributeError 失败时调用(要么 __getattribute__() 引发了一个 AttributeError,因为 name 不是实例属性,要么是 self 的类树中的属性;[...]

回答原始问题:你应该引发一个 AttributeError 或继承自 AttributeError 的自定义异常。如果不这样做,将破坏标准行为。

注意:根据你的用例,可能希望使用 __getattr__ 而不是 __getattribute__

英文:

The reason is actually just above the documentation you linked, __getattr__ depends on the AttributeError being raised to work correctly. From the documentation of __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; [...]

To answer the original question: You should raise either an AttributeError or a custom exception that inherits from AttributeError. Not doing so will break the standard behaviour.

Note: Depending on your use-case you may want to be using __getattr__ instead.

huangapple
  • 本文由 发表于 2020年1月3日 20:48:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定