python中特殊函数__call__()

背景

本文章介绍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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
,类的`__call__`方法是一个特殊方法。当一个类的实例对象被调用时,就会执行该实例对象的`__call__`方法的代码。 举个例子来说明,假设我们有一个类叫做Person,其定义了`__call__`方法。当我们创建一个Person的实例对象d时,我们可以像调用函数一样直接调用d,即`d()`。这样就会执行`__call__`方法的代码,输出"Method __call__() is called"。 所以,`__call__`方法可以让一个类的实例对象具有可调用的行为,就像调用函数一样。这在某些场景下可以提供更灵活的功能实现。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [python的__call__是什么?](https://blog.csdn.net/qq_37142216/article/details/129959609)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [详解Python的__call__()方法](https://blog.csdn.net/abigdream984/article/details/117932902)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值