“\uu getattribute”和“\uu getattr”中的错误处理__`

2024-03-28 14:59:22 发布

您现在位置:Python中文网/ 问答频道 /正文

注意这些问题在评论中得到了回答

我注意到在__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 an AttributeError.

由此,我可以猜到在__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__'),它们适用吗?你知道吗


Tags: theinselfnone属性valuedef评论
1条回答
网友
1楼 · 发布于 2024-03-28 14:59:22

总结评论。你知道吗

[Python 3.Docs]: Data model - object.__getattribute__(self, name)强调是我的)声明:

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 an AttributeError. This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

混淆是因为假设\uu getattr\uuem>是从对象继承的(这是错误的):

>>> dir(object)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>>
>>> object.__getattribute__
<slot wrapper '__getattribute__' of 'object' objects>
>>> object.__getattr__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'object' has no attribute '__getattr__'

尽管我能理解为什么有些人会感到困惑,但从我所关心的(在多次查看doc之后),很明显:
如果\u getattr\uuum>是从object继承的,那么(引用的)文本“如果该类还定义了uu getattr\uuuu()”就没有意义了。你知道吗

相关问题 更多 >