Possible Duplicate:
Can a class method be a decorator?
here's an example.
class myclass: def __init__(self): self.start = False def check(self): return not self.start def doA(self): if self.check(): return print('A') def doB(self): if self.check(): return print('B')
as you see,i want to write the check action in a decorator way, but after i tried many times, i found i can only write the method outside my class.please teach me how to write it inside the class ,thanks
edit:
i can write the code in this way:
def check(func): def checked(self): if not self.start: return func(self) return checked class myclass: def __init__(self): self.start = False @check def doA(self): print('A') @check def doB(self): print('B') a = myclass() a.doA() a.doB() a.start = True a.doA() a.doB()
but i don't think it's a good practice, i want to defined the check method inside my class.
Inside Class A “fun1” Instance Method is calling the decorator function “Decorators” inside Class B “fun2”. Instance Method is calling the decorator function of Class A. To use the decorator of Class A, we must require using Class name in which decorator is present that's why we use “@A. Decorators” here.
To decorate a method in a class, first use the '@' symbol followed by the name of the decorator function. A decorator is simply a function that takes a function as an argument and returns yet another function. Here, when we decorate, multiply_together with integer_check, the integer function gets called.
In Python, decorators can be either functions or classes. In both cases, decorating adds functionality to existing functions.
Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates several effects together. It is also known as nested decorators in Python.
While I don't think this is completely needed all the time, here is how you would make a decorator within your class. It is a little more cumbersome because of the way the methods become bound to the self
later on. Normally with plain function decorators you don't have to worry about that.
The requirements are:
functools.wraps
to preserve the bound methods properlyExample:
from functools import wraps class myclass: def __init__(self): self.start = False def _with_check(f): @wraps(f) def wrapped(inst, *args, **kwargs): if inst.check(): return return f(inst, *args, **kwargs) return wrapped def check(self): return self.start @_with_check def doA(self): print('A') @_with_check def doB(self): print('B')
I made it a protected member since it is not really something someone else needs to use outside of the class. And it still preserves your public check()
call for use by itself. The decorator simply wraps calling it first before calling the target method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With