After studying this issue Python. Calling a decorator inside a class

I decided to use this method to write a decorator inside a class. It checks the values ​​of one method and, depending on the response, either performs the additional method or executes. To put this all into a separate method will not work, since such a construction must be applied to all other methods. But still crawling errors. Has anyone encountered similar problems?

class A: def __init__(self): pass def _refresh(func1,func2,func3): def checker(self): if func2: func3 func1 return checker def switcher(self): return True def prep(self): self.m = 100 def diver(self): self.m = self.m / 4 @_refresh(switcher(), diver()) def prep1(self): self.b=self.m/2 

    1 answer 1

     # функция, принимающая аргументы и возвращающая декоратор def _refresh(func2, func3): # сам декоратор def decorator(func1): # функция-обертка, заменит собой декорируемую def wrapper(self, *args, **kwargs): if func2(self): func3(self) func1(self, *args, **kwargs) # декоратор возвращает обертку return wrapper # возаращаем сам декоратор return decorator 

    only this is not a particularly suitable case for using decorators

    Upd:

    Oh yeah, I forgot to mention: you need to apply a little bit differently, as in your example.

     @_refresh(switcher, diver) def prep1(self): self.b=self.m/2 

    those. pass the functions themselves as arguments, not the result of their execution.

    For more flexibility, you can do this:

     @_refresh(lambda self: self.switcher(), lambda self: self.diver()) def prep1(self): self.b=self.m/2 

    Well, commented at the same time.

    • unfortunately, how to check the state of a variable in a different way, which can change at any time (you can only check it by a separate method) and can affect the execution of all methods - until you’ve thought it up :( - SimonZen
    • 3
      In a good program, there are no surprises. if a variable is a class field, and it can be changed from the outside, it should be arranged in the form of a setter, in which, in addition to direct change, do all the related work of maintaining the class invariant. For example, using the standard decorator @property (the information is there ) - extrn