我有一个计算工资组成部分的类,如下所示。
def normalize(func):
from functools import wraps
@wraps(func)
def wrapper(instance, *args, **kwargs):
allowanceToCheck = func(instance)
if instance.remainingAmount <= 0:
allowanceToCheck = 0.0
elif allowanceToCheck > instance.remainingAmount:
allowanceToCheck = instance.remainingAmount
instance.remainingAmount = instance.remainingAmount - allowanceToCheck
return allowanceToCheck
return wrapper
class SalaryBreakUpRule(object):
grossPay = 0.0
remainingAmount = 0.0
@property
def basic(self):
# calculates the basic pay according to predefined salary slabs.
basic = 6600 # Defaulting to 6600 for now.
self.remainingAmount = self.grossPay - basic
return basic
@property
@normalize
def dearnessAllowance(self):
return self.basic * 0.2
@property
@normalize
def houseRentAllowance(self):
return self.basic * 0.4
def calculateBreakUps(self, value = 0.0):
self.grossPay = value
return {
'basic' : self.basic,
'da' : self.dearnessAllowance,
'hra' : self.houseRentAllowance
}
在计算每个津贴之前,我需要检查所有津贴的总和是否不超过grossPay,即我的总工资。我写了一个装饰器,它包装了每个津贴计算方法并完成了上述要求。例如,
* an employee having a salary of Rs.6700
* basic = 6,600 (according to slab)
* dearnessAllowance = 100 (cos 20% of basic is more than remaining amount)
* houseRentAllowance = 0.0 (cos 40% of basic is more than remaining amount)
但不幸的是,它没有用。第一津贴计算正确,但所有其他津贴的值与第一津贴相同。即 houseRentAllowance 将有 100 而不是上面给出的 0.0。
我发现的问题是,代码行
instance.remainingAmount = instance.remainingAmount - allowanceToCheck
在我试图设置类变量的装饰器中不起作用。
有什么办法可以解决这个问题吗?