先看示例,然后啥都明白了

class Student():
    def __call__(self, *args, **kwargs):
        print('__call__方法被调用', *args)

class Person():
    def mm(self):
        print('mm方法被调用')

测试代码 :

from test.student import Student, Person

if __name__ == '__main__':
    student =Student()
    student('ni nai nai de ')

    print('*'*40)
    person = Person()
    person()

打印结果:

C:\Users\zhengqinfeng\AppData\Local\Programs\Python\Python37\python.exe E:/ws/python/LearnFlask/test/xx.py
Traceback (most recent call last):
__call__方法被调用 ni nai nai de 
  File "E:/ws/python/LearnFlask/test/xx.py", line 9, in <module>
****************************************
    person()
TypeError: 'Person' object is not callable

Process finished with exit code 1

 

结论: Student对象的正常调用,而Person调用报错,一切都是因为__call__方法,  它就是对象的回调方法。。。。

 

 补充: 对象+() 即是调用__call__方法

 

posted on 2019-11-29 22:56  显示账号  阅读(394)  评论(0)    收藏  举报