[PYTHON] a () and a.__ call__ () are not equivalent

As the title says, I didn't know it, so I made a note for myself.

When you override ʻa .__ call __ () and ʻa (), you can see that they actually have different __ behavior . It seems that ʻa ()callstype (a) . call __ (a)` to be exact.

python


>>> class A(object):
...     def __init__(self):
...         print 'init of A'
...         
...     def __call__(self):
...         print 'call of A'
...         
...     def method(self):
...         print 'method of A'
...         

Define __init__, __call__, method in the class A. Since method is an ordinary member function, you can override the method by setting ʻa.method = hoge`.

python


#Check the processing when calling normally
>>> a = A()
init of A
>>> a.method()
method of A
>>> a()
call of A

# a.Try overwriting method
>>> a.method = lambda: 'overriding method'
>>> a.method()
'overriding method'

# a.__call__Overwrite in the same way
>>> a.__call__ = lambda: 'overriding call'

# a.__call__()Is certainly overridden
>>> a.__call__()
'overriding call'

# a()It doesn't work
>>> a()
call of A
>>> type(a).__call__(a)
call of A

# type(a).__call__Forcibly overwrite
>>> type(a).__call__ = lambda a: 'new __call__'
>>> type(a).__call__(a)
'new __call__'

#Worked well
>>> a()
'new __call__'

reference

http://www.rakunet.org/tsnet/TSpython/43/1292.html

Recommended Posts

a () and a.__ call__ () are not equivalent
Python a + = b and a = a + b are different
[Python3] "A // B" and "math.floor (A / B)" are not always the same! ??
python memo-"if not A and B" was "if (not A) and B"
A note about __call__
A solution to the problem that files containing [and] are not listed in glob.glob ()
Python default arguments are not initialized on every call
Python and pip commands are not available on CentOS (RHEL) 8
How to call a function
Read and write a file
Python list is not a list
A1 notation and 26-ary number
Write and read a file
What is a system call
Difference between ps a and ps -a
A python regular expression, str and unicode that are sober and addictive
Upload and manage packages that are not in conda to anaconda.org