Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between __init__ and __call__?

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 
like image 230
sam Avatar asked Mar 12 '12 08:03

sam


People also ask

What does __ call __ do in Python?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.

What is __ init __ called?

"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.

Can you call methods in __ init __?

You cannot call them explicitly. For instance, when you create a new object, Python automatically calls the __new__ method, which in turn calls the __init__ method. The __str__ method is called when you print() an object.

What is __ init __ used for?

"__init__" is a reseved method in python classes. It is known as a constructor in object oriented concepts. This method called when an object is created from the class and it allow the class to initialize the attributes of a class.


1 Answers

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__ 
like image 173
Cat Plus Plus Avatar answered Oct 04 '22 14:10

Cat Plus Plus