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
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.
"__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.
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.
"__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.
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__
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With