英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论