Just started learning python, I've come across __call__
method. I understand when __init__
gets called and when __call__
gets called by running a simple example:
class Constructor:
def __init__(self, a):
print "__init__ called"
def __call__(self):
print "__call__ called"
def dummy(self):
print "a dummy method called"
print "creating x obj"
x = Constructor(1)
print "calling x object"
x()
console output:
creating x obj
__init__ called
calling x object
__call__ called
My questions are:
- I come from java background, I know
__init__
maps to java constructor, does java have an equivalent to__call__
to help me understand this better? - Can someone give me a simple example of when
__call__
can be useful?
__call__
is a base of the language (see eli.thegreenplace.net/2012/03/23/…) and helpfull to solving several problems/tasks like observer pattern, callback and so on.