Feb 27, 2019

What is the difference between __init__ and __call__?

# __init__ method is used when the class is called to initialize the instance
# while the __call__ method is called when the instance is called

class Foo:
    def __init__(self, a, b, c):
        print 'inside Foo __init__'
    def __call__(self, a, b, c):
        print 'inside Foo __call__'

class Bar:
    def __init__(self):
        print 'inside Bar __init__'
    def __call__(self, a, b, c):
        print 'inside Bar __call__'


f = Foo(1, 2, 3) # __init__
b = Bar()
b(1, 2, 3) # __call__


Output:
inside Foo __init__
inside Bar __init__
inside Bar __call__

No comments:

Post a Comment