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'''
__call__魔法方法的使用样例
最新推荐文章于 2023-09-20 18:44:57 发布