How do I implement __getattribute__ without an infinite recursion error?

前端 未结 6 1374
天命终不由人
天命终不由人 2020-11-27 10:18

I want to override access to one variable in a class, but return all others normally. How do I accomplish this with __getattribute__?

I tried the follo

6条回答
  •  盖世英雄少女心
    2020-11-27 10:42

    Python language reference:

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

    Meaning:

    def __getattribute__(self,name):
        ...
            return self.__dict__[name]
    

    You're calling for an attribute called __dict__. Because it's an attribute, __getattribute__ gets called in search for __dict__ which calls __getattribute__ which calls ... yada yada yada

    return  object.__getattribute__(self, name)
    

    Using the base classes __getattribute__ helps finding the real attribute.

提交回复
热议问题