背景
本文章介绍python中特殊函数__call__()
作用
call()相当于重载了()运算符,可以使类对象像函数一样被调用。
代码块
代码中没有__call__()方法,运行如下:
class TestCall():
def test_func(self):
print "test"
f = TestCall()
f()
# 执行结果
Traceback (most recent call last):
File "/Users/test_pytest/aaa_pytest.py", line 18, in <module>
f()
AttributeError: TestCall instance has no __call__ method
结论
TestCall类中没有__call__()方法,直接运行,程序抛出异常
代码中有__call__()方法,运行如下:
class TestCall():
def __call__(self, *args, **kwargs):
print "call"
f = TestCall()
f()
# 执行结果
call
结论
TestCall类中存在__call__()方法,对象f通过__call__(self, *args, **kwargs)方法可以模拟函数行为。f(arg1,arg2)等同于f. __call__(arg1,arg2)
探讨片
利用__call__()方法封装成装饰器,提前封装好request类,构造好接口请求参数后,可在该func上添加此装饰器完成接口请求
class TestCall():
def __call__(self, func):
self.func = func
def fun_wapper( *args, **kwargs):
self.func_return = self.func(*args, **kwargs) or {}
return requests(self.method, self.url, self.session, self.func_doc, self.decorator_args)
return fun_wapper