How to pass instance into decorator function

Jayakrishnan Damodaran jakyjk05 at gmail.com
Thu Jun 13 06:40:02 EDT 2013


I have a class which calculates some salary allowances. Instead of a blind calculation I need to check some conditions before I can return the calculated amount. Like if all the allowances calculated till now plus the one in progress must not exceed the total salary(this may occur since these allowances are a percentage of basic pay). Below is a sample code FYI

class CompanySalaryBreakUpRule(object):
    '''Class to calculate the various salary components.
    This class is inherited by individual company classes whom implement salary calculations.
    Various component calculations are implemented as @property and hence be accessed as class properties.

    '''
    grossPay = 0.0
    remainingAmount = 0.0

    def checkValid(self, func):
        from functools import wraps

        @wraps(func)
        def wrapper(self, *args, **kwargs):
            allowanceToCheck = func(self, *args, **kwargs)
            if allowanceToCheck > self.remainingAmount:
                allowanceToCheck = self.remainingAmount
            else:
                self.remainingAmount = self.remainingAmount - allowanceToCheck
            return allowanceToCheck
        return wrapper
    
    @property
    @checkValid
    def dearnessAllowance(self):
        return self.basic * 0.2 # we have a function that calculates basic pay

But executing this raises an exception
@checkValid
TypeError: checkValid() takes exactly 2 arguments (0 given)



More information about the Python-list mailing list