What is the difference between __init__ and __call__?

sam picture sam · Mar 12, 2012 · Viewed 266.9k times · Source

I want to know the difference between __init__ and __call__ methods.

For example:

class test:

  def __init__(self):
    self.a = 10

  def __call__(self): 
    b = 20

Answer

Cat Plus Plus picture Cat Plus Plus · Mar 12, 2012

The first is used to initialise newly created object, and receives arguments used to do that:

class Foo:
    def __init__(self, a, b, c):
        # ...

x = Foo(1, 2, 3) # __init__

The second implements function call operator.

class Foo:
    def __call__(self, a, b, c):
        # ...

x = Foo()
x(1, 2, 3) # __call__