Python __call__ 用法 作用

本文详细介绍了Python中对象的可调用性概念,通过示例解释了如何使用callable函数判断对象是否可调用,并展示了如何通过定义__call__方法使类实例成为可调用对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Python中的对象有可被调用和不可被调用之分。

def func_test():
    print("func_test run")
 
class class_test():
    def __init__(self):
        pass
 
# func_test is callable return True
print("func_test is callable return:%s" % callable(func_test))
# class_test() is not callable return False
print("class_test() is not callable return:%s" % callable(class_test()))
a = class_test()
# a is not callable return False
print("a is not callable return:%s" % callable(a))
print("this means the instance is not callable")

输出

func_test is callable return:True
class_test() is not callable return:False
a is not callable return:False
this means the instance is not callable

上面的例子说明,实例是不可以被调用的。实际中写代码时可能会遇到需要调用实例。

python 中的__call__方法可以解决这个问题

class class_test():
    def __init__(self):
        print("run class __init__")
 
    def __call__(self):
        print("run class __call__")
 
print("class_test() is not callable return:%s" % callable(class_test()))
 
class_test()
 
a = class_test()
print("a is not callable return:%s" % callable(a))
 
a()

输出

run class __init__
class_test() is not callable return:True
run class __init__
run class __init__
a is not callable return:True
run class __call__

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值