__call__()的用法
__call__()方法能够让类的实例对象,像函数一样被调用;
>>> >>> class A(object): def __call__(self, x): print(‘__call__ called, print x: ‘, x) >>> >>> a = A() >>> a(‘123‘) __call__ called, print x: 123 >>>
看a(‘123‘)这是函数的调用方法,这里a实际上是类对象A的实例对象,实例对象能想函数一样传参并被调用,就是__call__()方法的功能;
接下来用一段简单的代码,来总体感受一下三个方法的用法和区别:
>>> >>> class A(object): def __init__(self, x): print (‘x in __init__‘, x) def __new__(cls, y): print ‘y in __new__‘, y return super(A, cls).__new__(cls) def __call__(self, z): print( ‘z in __call__‘, z) >>> >>> A(‘123‘)(‘abc‘) y in __new__ 123 x in __init__ 123 z in __call__ abc >>>
由执行结果可以看出,虽然__init__()方法定义在__new__()方法之前,但是结果中先展示了__new__()方法的执行结果;
原文地址:https://www.cnblogs.com/linwenbin/p/10326232.html
时间: 2024-10-17 06:51:19