可调用对象

    科技2026-01-05  11

    class instance: def __init__(self,x): self.x = x print("be in __init__ method") def test(self): print("be in test method") def __call__(self): print("be in __call__ method") self.called() def called(self): print("be in called method") 实例化 a = instance(3)

    输出

    be in __init__ method 调用__call__方法 a() #一般类是没有这种语法的,这里是因为我们给它写了__call__方法。

    等同于

    a.__call__()

    输出

    be in __call__ method be in called method 调用类中的其它方法 a.test() #说明__call__方法的使用并不会屏蔽其它方法的调用

    输出

    be in test method 将类实例化为同名对象 instance(2) #就算类的定义没有设置位置参数x,如instance(),初始化方法的优先级也是高于__call__方法的。

    输出

    be in __init__ method <__main__.instance object at 0x0000022D9DBC3E88>

    拓展

    Processed: 0.039, SQL: 9