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 ()calls
type (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__'
http://www.rakunet.org/tsnet/TSpython/43/1292.html
Recommended Posts