This example describes the use of __call__ in Python and shares it for your reference. The specific methods are as follows:
Let's take a look at the following sample code:
#call. py A class is loaded in the case.
class Next:
List = []
def __init__ (Self,low,high): for
Num in range (Low,high):
self. List.append (Num * * 2)
def __call__ (self,nu): Return
self. LIST[NU]
If you use this:
b = Next (1,7)
print b.list
print B (2)
Then feedback is normal:
But if you use this:
b = Next
B (1,7)
print b.list
print B (2)
$python./call.py
[1, 4, 9,,,]
traceback ( Most recent called last):
File "cal.py", line <module>
print B (2)
TypeError: __init__ () takes ex actly 3 Arguments (2 given)
__INIT__ is an initialization function that is executed when an instance of the class is generated.
And __call__ is an impersonation () call that needs to be applied on an instance, so this instance is naturally already executed __init__.
The following example that you have raised:
This is not to create an instance, but to assign the class to a variable. So the next operation with B is the operation of the following class, which is actually:
Next (1,7)
print next.list
print next (2)
I hope this article will help you with your Python programming.