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__方法

  • 相关阅读:
    架构阅读笔记4
    python读取docx内容
    python转换doc为docx
    使用Navicat连接oracle问题及解决
    扩充虚拟机磁盘
    虚拟机无法打开内核
    六个常见属性场景
    架构阅读笔记3
    架构学习
    PHP中的加密方式有如下几种
  • 原文地址:https://www.cnblogs.com/z-qinfeng/p/11960834.html
Copyright © 2011-2022 走看看