'super' object not calling __getattr__

后端 未结 1 1903
一生所求
一生所求 2020-12-06 04:56

I have one object wrapped inside another. The \"Wrapper\" accesses the attributes from the \"Wrapped\" object by overriding __getattr__. This works well until I

相关标签:
1条回答
  • 2020-12-06 05:29

    According to this, super does not allow implicit calls of "hook" functions such as __getattr__. I'm not sure why it is implemented this way (there's probably a good reason and things are already confusing enough since the super object has custom __getattribute__ and __get__ methods as it is), but it seems like it's just the way things are.

    Edit: This post appears to clear things up a little. It looks like the problem is the extra layer of indirection caused by __getattribute__ is ignored when calling functions implicitly. Doing foo.x is equivalent to

    foo.__getattr__(x)
    

    (Assuming no __getattribute__ method is defined and x is not in foo.__dict__) However, it is NOT equivalent to

    foo.__getattribute__('__getattr__')(x)
    

    Since super returns a proxy object, it has an extra layer of indirection which causes things to fail.

    P.S. The self.__dict__ check in your __getattr__ function is completely unnecessary. __getattr__ is only called if the attribute doesn't already exist in your dict. (Use __getattribute__ if you want it to always be called, but then you have to be very careful, because even something simple like if name in self.__dict__ will cause infinite recursion.

    0 讨论(0)
提交回复
热议问题