__call__魔法方法的使用样例

def CalTime(func):
    def In():
        start = time.process_time()
        func()
        end = time.process_time()
        calltime= end-start
        print(calltime)
    return In

print(callable(CalTime))
'''result --> True'''
class BB:
    pass

#callable 函数检查内容是可调用的对象,比如函数?但是实例后的对象就不可调用了
print(callable(BB))
'''result --> True'''
b = BB() #实例化类BB
print(callable(b))
'''result --> False'''



class B:
    def __init__(self):
        pass
    def __call__(self, *args, **kwargs):
        return [i for i in range(10)]
print(callable(B))
'''result --> True'''

b = B() #实例化B类
print(b())
'''result --> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'''


#修饰符可以装饰函数,也可以装饰__call__方法后的对象函数
#只是需要将实例化的动作定义为函数
@CalTime
def a():
    b = B()
    return b()
print(a())
'''这就打印出了class B的运行时间
result --> 4.9999999999980616e-06'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值