1

Even If I could initialize a class attribute to do this, for readability reasons I try to use decorators to simulate static variables within a class method. It works perfectly in a standard function, but not with class methods.

I cannot understand why I get: AttributeError: 'method' object has no attribute 'inc' each time I run the following code despite the print line is able to get the value of self.totofunc.inc. It is the self.totofunc.inc += 1 which triggers the error.

Does someone can help me to understand?

Thanks in advance

def static(dict_var_val):
    def staticf(f):
        def decorated(*args, **kwargs):
            f(*args, **kwargs)
        for var,val in dict_var_val.items():
            setattr(decorated, var, val)
        return decorated
    return staticf

class toto:
    def __init__(self):
        pass

    @static({'inc':3})
    def totofunc(self):
        print("static : {}".format(self.totofunc.inc))
        self.totofunc.inc += 1


inst=toto()

for i in range(1,3):
    inst.totofunc()
vaultah
  • 44,105
  • 12
  • 114
  • 143
Guilmort
  • 41
  • 1
  • 5

0 Answers0