Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19k points)

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

For example:

class test:

    def __init__(self):

        self.a = 10

    def __call__(self):

        b = 20

2 Answers

0 votes
by (106k points)

The __init__   method is used to initialise the newly created object, and it receives arguments that are used to initialize the newly created object.

class Foo:

    def __init__(self, a, b, c):

        x = Foo(1, 2, 3) # This is the __init__ method.

The call() method is used to implement the function call operator.

class Foo:

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

          x = Foo()

          x(1, 2, 3) #This is the call() method.

0 votes
by (108k points)
edited by

Please be informed that the __init__() is the way of defining the constructor of the class in Python and a custom __call__() method in the meta-class enables the class's object to be described as a function, not always modifying the instance itself.

In [1]: class A:

   ...:     def __init__(self):

   ...:         print "init"

   ...:         

   ...:     def __call__(self):

   ...:         print "call"

   ...:         

   ...:         

In [2]: a = A()

init

In [3]: a()

call

For more information regarding the same do refer to the below Python tutorial video:

Related questions

0 votes
1 answer
asked Jun 27, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...