Python There are some magical ways to do it , They are always surrounded by double underscores , They are object-oriented Of Python Everything . They are special ways to add magic to your classes , If your object implements ( heavy load ) A magic method , Then this method will be automatically used in special cases Python The call .
Allow and define the behavior of an object when it is called like a function .
self Represents the object itself ,args and kwargs Represents two indefinite length parameters .
Any number and type of objects .
class MyText(object):
def __call__(self, *args, **kwargs):
my_sum = 0
for item in args:
my_sum += item
return my_sum
sample = MyText()
print(sample(1, 2, 3, 4, 5))
__call__() It's a kind of magic method, Implementing this method in a class can make instances of that class ( object ) Called like a function . By default, this method is not implemented in the class . Use callable() Method can determine whether an object can be called .
__call__() Method is actually used to turn an instantiated object of a class into a callable object , That is to say, an instantiated object of a class becomes a callable object , As long as the class implements __call__() The method will do .
class People(object):
def __init__(self, name):
self.name = name
def __call__(self):
print("hello " + self.name)
a = People(' No taboo !')
a.__call__() # Call method 1
a() # Call method 2
When writing a class , If it's written __call__() Method , When the instantiated object is called, there will be Instance object point __call__() and object() These two ways of use have the same effect , That is, calling method 1 has the same effect as calling method 2 .