Asymmetric behavior for __getattr__, newstyle vs oldstyle classes

流过昼夜 提交于 2019-11-28 09:23:05
lunaryorn

See Special method lookup for new-style classes.

Special methods are directly looked up in the class object, the instance objects and consequently __getattr__() and __getattribute__() are bypassed. For precisely the same reason, instance.__add__ = foobar doesn't work.

This is done to speed up attribute access. Special methods are called very frequently, and making them subject to the standard, rather complex attribute lookup would significantly slow down the interpreter.

Attribute lookup for old-style classes is much less complex (most notably old style classes do not support descriptors), so there is no reason to treat special methods differently in old style classes.

Your __getattr__ functions aren't returning anything. I don't know why the old-style class is doing the __getattr__ before looking for __add__, but it is, and this is trying to call the return value which is None.

The new-style class is doing it right: you haven't defined __add__ so it doesn't know how to add them.

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