python built-in functions vs magic functions and overriding [duplicate]

試著忘記壹切 提交于 2019-12-02 02:06:35

As linked by user1579844 what is happening is that the new-style classes avoid the normal lookup mechanism of __getattribute__ and load directly the method when the interpreter call them. This is done for performance reasons, being the magic method so common that the standard lookup would slow down terribly the system.

When you explicitly call them with the dot notation you are falling back to the standard lookup and so you call the __getattribute__ first.

If you are working in python 2.7 you can avoid this behavior using old style classes, otherwise look to the answers in the thread suggested to find some solution.

when you called

a.__str__ 

it was considered

__str__

as item in the constructor .

def __getattribute__(self, item):
        print 'custom__getattribute__ - ' + item
        return ''

in this line :

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