class Employee:
def __init__(self,func):
self.func = func
def __call__(self,*args,**kwargs):
self.count += sum(args)
return self.count
@Employee
def getJob(a,b):
return a+b
getJob(2,3)
这段代码我想求和,为啥求不了
主要问题有三个:
未初始化的 count 属性:
你在 call 中使用了 self.count,但从未在 init 中初始化这个属性
导致报错:AttributeError: 'Employee' object has no attribute 'count'
逻辑矛盾:
装饰器应该增强原函数功能,但你的代码完全替代了原函数行为
原 getJob(a,b) 的功能(返回 a+b)被丢弃了
返回值问题:
call 返回的是累加值,不是原函数的计算结果
class Employee:
def __init__(self, func):
self.func = func
self.call_count = 0 # 用于统计调用次数
def __call__(self, *args, **kwargs):
self.call_count += 1
# 先执行原函数逻辑
result = self.func(*args, **kwargs)
print(f"已调用 {self.call_count} 次,本次结果: {result}")
return result # 返回原函数的结果
@Employee
def getJob(a, b):
return a + b
print(getJob(2, 3)) # 输出: 5 (同时会打印调用信息)