如何在不破坏默认行为的情况下覆盖 __getattr__ ?
如何覆盖 __getattr__
类的方法而不破坏默认行为?
How do I override the __getattr__
method of a class without breaking the default behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
重写
__getattr__
应该没问题——__getattr__
仅作为最后的手段被调用,即如果实例中没有与名称匹配的属性。例如,如果您访问foo.bar
,则仅当foo
没有名为bar
的属性时才会调用__getattr__
>。如果您不想处理该属性,请引发AttributeError
:但是,与
__getattr__
不同,__getattribute__
将首先被调用(仅适用)对于新样式类,即从对象继承的类)。在这种情况下,您可以保留默认行为,如下所示:请参阅Python 文档了解更多信息。
Overriding
__getattr__
should be fine --__getattr__
is only called as a last resort i.e. if there are no attributes in the instance that match the name. For instance, if you accessfoo.bar
, then__getattr__
will only be called iffoo
has no attribute calledbar
. If the attribute is one you don't want to handle, raiseAttributeError
:However, unlike
__getattr__
,__getattribute__
will be called first (only works for new style classes i.e. those that inherit from object). In this case, you can preserve default behaviour like so:See the Python docs for more.
为了扩展迈克尔的答案,如果您想使用
__getattr__
维护默认行为,您可以这样做:现在异常消息更具描述性:
To extend Michael answer, if you want to maintain the default behavior using
__getattr__
, you can do it like so:Now the exception message is more descriptive:
人们在这次讨论中忽略了一件重要的事情——如果你的类不是抽象的并且你收到名称为“__isabstractmethod__”的 getattr,Python 需要在 __getattr__ 中引发 AttributeError。
There is one important thing people are missing in this discussion - Python requires to raise AttributeError in __getattr__ if your class isn't abstract and you receive getattr of name: '__isabstractmethod__'.