注意这些问题在评论中得到了回答
我注意到在__getattribute__
和__getattr__
中有一些异常处理的行为,我在文档或其他文章中找不到。你知道吗
考虑这个类A
。如果A
的实例具有None
属性,则访问该属性会引发AttributeError
。你知道吗
class A:
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if value is None:
raise AttributeError('in __getattribute__')
return value
def __init__(self, a=None):
self.a = a
A(1).a # 1
A().a # raises AttributeError('in __getattribute__')
现在,__getattribute__
上的docs说
Called unconditionally to implement attribute accesses for instances of the class. If the class also defines
__getattr__()
, the latter will not be called unless__getattribute__()
either calls it explicitly or raises anAttributeError
.
由此,我可以猜到在__getattribute__
中引发的任何AttributeError
都会被捕获,并且进程延迟到__getattr__
,这样AttributeError('in __getattribute__')
就永远不会被调用方看到。你知道吗
令我惊讶的是,不仅看到了错误,而且在A().a
上引发的AttributeError
就是__getattribute__
中的那个,就好像__getattr__
从未被调用过一样。这是除非__getattr__
提出自己的问题
def __getattr__(self, item):
raise AttributeError('in __getattr__')
在这种情况下,我们会看到AttributeError('in __getattr__')
被提升。你知道吗
这里有什么规定?如果我在__getattribute__
中提出了AttributeError
的一些子类Oops
,而不是AttributeError('in __getattribute__')
,它们适用吗?你知道吗
总结评论。你知道吗
[Python 3.Docs]: Data model - object.__getattribute__(self, name)(强调是我的)声明:
混淆是因为假设\uu getattr\uuem>是从对象继承的(这是错误的):
尽管我能理解为什么有些人会感到困惑,但从我所关心的(在多次查看doc之后),很明显:
如果\u getattr\uuum>是从object继承的,那么(引用的)文本“如果该类还定义了uu getattr\uuuu()”就没有意义了。你知道吗
相关问题 更多 >
编程相关推荐