zoukankan      html  css  js  c++  java
  • python对象之__call__方法

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

    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:UserszhengqinfengAppDataLocalProgramsPythonPython37python.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__方法

  • 相关阅读:
    TinyOS功率编程指南
    深度学习入门资料
    通信常识
    CTF入门
    前端开发工具之服务器选择
    Spring
    NoSQL -- MongoDB
    NoSQL -- Redis
    mysql alter table修改表结构添加多个字段的几个写法
    gongle 访问助手安装
  • 原文地址:https://www.cnblogs.com/z-qinfeng/p/11960834.html
Copyright © 2011-2022 走看看