Dynamically overriding __functions__ in Python

Let's say I want to override a type function __int__in a Python class so that I can do something like this.

class A(object):
    def __init__(self):
        self.__int__ = lambda: 1

a = A()
print int(a)

I expect "1" to be displayed here instead of causing this error message

Argument TypeError: int () must be a string or a number, not "A"

When __int__instead it becomes a method embedded in a class, it works as expected. What for? (This problem exists for any of the double underscore functions)

+4
source share
2 answers

In magic methods __, another magic of magic appears. Unlike other methods, they do not look for class instances when they are invoked implicitly.

, __getattribute__ ( , , __getattribute__ , ). .

, "Special Method Lookup": http://segfaulthunter.imtqy.com/articles/biggestsurprise/

, , . , __str__ str(). , .

, - .

+3

, , :

class A(object):
    def __init__(self):
        self.a_fun = lambda: 1

:

class A(object):
    def __init__(self):
        self._int = 1

    def a_fun(self):
        return self._int

, , . , _int .

, :

class A(object):
    def __init__(self):
        self.__int__ = lambda: 1

class A(object):
    def __init__(self):
        self._int = 1

    def __int__(self):
        return self._int

: , - . , , . .

, , , . Python, .; -)

+1

All Articles