python call function

Reference blog: The essence of the call function call() in python3 is to turn a class into a function (so that instances of this class can be called like functions).

class person:
    def __call__(self, name):
        print('__call__, '+'Hello,'+name)
    def hello(self,name):
        print('hello,'+name)

person = person()
person('zhangsan')
person.hello('lisi')#对比结果可以看到内置call函数无非就是可以直接用类名调用函数,而不用像person.hello()来调用函数

Running results:
insert image description here
From the comparison results, we can see that the built-in call function is nothing more than calling the function directly with the class name instead of calling the function like person.hello().

class person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __call__(self, male):
        print('my name is %s' % self.name)
        print('my age is %s' % self.age)
        print('my male is %s' % male)


if __name__ == '__main__':
    a = person('jack', 26)
    a('男')

The class person defined here requires two parameters, a name and an age. After we pass in the parameters, we have an instance a, and the direct call of the instance a is the call method. This method makes the class a a function, which can be called , you can also add parameters to it.
operation result:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_44769034/article/details/124302794