When creating a class, I use init a lot, but when I get call, I interpret it in my own way.
The environment is Python 3.5.1 :: Anaconda 2.5.0 (x86_64) Run on Jupyter notebook
__call__
is activated when called like a functionClass example
class_sample.py
class A:
def __init__(self, a):
self.a = a
print("A init")
def __call__(self, b):
print("A call")
print(b + self.a)
class B(A):
def __init__(self, a, c):
super().__init__(a)
self.c = c
print("B init")
def __call__(self, d):
print("B call")
print(self.a + self.c + d)
Execution example
>>> a = A(1)
A init
>>> a(2)
A call
3
>>> b = B(1,3)
A init
B init
>>> b(4)
B call
8
Only __init__
is called for instantiation. However, if you call the created instance with arguments like a function, __call__
will be called.
Of course, if you give a return value to __call__
, you can use the value obtained from the instance for another variable.
Recommended Posts