Python中__call__方法总结

版权声明: https://blog.csdn.net/csdnwgf/article/details/80146854

Python中万物都可称为对象,但对象与对象之间也有差别。对象有可被调用不可被调用之分。

当一个对象为可被调用对象时,callable(object)返回为True,否则为False:

def test1():
	print('Hello test1')
	
class test2():
	def __init__(self):
		pass

# 函数为可调用对象,callable(test)返回为True
print(callable(test1))

a = test2()
# 实例是不可调用对象,callable(test)返回为False
print(callable(a))

从上面的例子可以看出,实例是不可以被调用的,但是实际在编写代码的时候有些场景恰恰需要调用实例,那该怎么办呢?Python中的__call__方法就可以解决这个问题:

class test2():
	def __init__(self):
		pass
		
	def __call__(self):
		print("Hello test2")

# 通过方法__call__,使得实例a可以被调用,callable(a)返回为True
a = test2()
print(callable(a))

# 像执行函数一样“执行”实例。输出:Hello test2
a() # 相当于执行a.__call__()

根据这个特性,可通过__call__方法来定义 类装饰器,具体如何实现等我有时间再写吧。

ღ( ´・ᴗ・` )比心


猜你喜欢

转载自blog.csdn.net/csdnwgf/article/details/80146854