Python built-in functions vs. magic functions and overriding

Possible duplicate:
Intercept operator lookup on metaclass
How to intercept calls for "magic" python methods in new style classes?

Consider the following code:

class ClassA(object):
    def __getattribute__(self, item):
        print 'custom__getattribute__ - ' + item
        return ''
    def __str__(self):
        print 'custom__str__'
        return ''

a=ClassA()
print 'a.__str__: ',
a.__str__

print 'str(a): ',
str(a)

      

The result was unexpected for me:

a.__str__:  custom__getattribute__ - __str__
str(a):  custom__str__

      

  • str(a)

    Should n't it be juxtaposed with a magical method a.__str__()

    ?
  • If I delete the custom ClassA.__str__()

    one then ClassA.__getattribute__()

    it still doesn't catch the call. Why?
+2


source to share


2 answers


As user1579844 related, what happens is that the new style classes escape the normal __getattribute__ lookup mechanism and load the method directly when the interpreter calls them. This is done for performance reasons, being a magical method so common that a standard search will slow the system down considerably.

When you explicitly call them using dot notation, you fall back to standard search and therefore call __getattribute__ first.



If you are running in python 2.7 you can avoid this behavior by using old style classes, otherwise look at the answers in the thread suggested for a solution.

+1


source


when calling

a.__str__ 

      

was considered

__str__

      



as item in the constructor.

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

      

on this line:

print 'custom__getattribute__ - ' + item  

      

0


source







All Articles