Which special methods bypasses __getattribute__ in Python?

别说谁变了你拦得住时间么 提交于 2019-11-27 13:45:27

You can find an answer in the python3 documentation for object.__getattribute__, which states:

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).

Note

This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions. See Special method lookup.

also this page explains exactly how this "machinery" works. Fundamentally __getattribute__ is called only when you access an attribute with the .(dot) operator(and also by hasattr as Zagorulkin pointed out).

Note that the page does not specify which special methods are implicitly looked up, so I deem that this hold for all of them(which you may find here.

Checked in 2.7.9

Couldn't find any way to bypass the call to __getattribute__, with any of the magical methods that are found on object or type:

# Preparation step: did this from the console
# magics = set(dir(object) + dir(type))
# got 38 names, for each of the names, wrote a.<that_name> to a file
# Ended up with this:

a.__module__
a.__base__
#...

Put this at the beginning of that file, which i renamed into a proper python module (asdf.py)

global_counter = 0

class Counter(object):
    def __getattribute__(self, name):
        # this will count how many times the method was called
        global global_counter
        global_counter += 1
        return super(Counter, self).__getattribute__(name)

a = Counter()
# after this comes the list of 38 attribute accessess
a.__module__
#...
a.__repr__
#...

print global_counter  # you're not gonna like it... it printer 38

Then i also tried to get each of those names by getattr and hasattr -> same result. __getattribute__ was called every time.

So if anyone has other ideas... I was too lazy to look inside C code for this, but I'm sure the answer lies somewhere there.

So either there's something that i'm not getting right, or the docs are lying.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!