HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonCriticalCanonical

What is the difference between __init__ and __call__?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
__call__andbetween__init__thedifferencewhat

Problem

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

Solution

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__

Code Snippets

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

x = Foo(1, 2, 3) # __init__
class Foo:
    def __call__(self, a, b, c):
        # ...

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

Context

Stack Overflow Q#9663562, score: 1088

Revisions (0)

No revisions yet.