How To Create A Decorator Function With Arguments On Python Class?
I want to create a decorator function to operate on a python class, with the ability to pass additional arguments. I want to do that before the class gets instantiated. Here is my
Solution 1:
You need to do it this way:
defmakeDeco(a):
defdeco(cls):
print cls, a
return cls
return deco
>>> @makeDeco(3)
... classFoo(object):
... pass
<class'__main__.Foo'> 3You can use functools.wraps and so forth to spruce it up, but that is the idea. You need to write a function that returns a decorator. The outer "decorator-making" function takes the a argument, and the inner decorator function takes the class.
The way it works is that when you write @makeDeco(3) it calls makeDeco(3). The return value of makeDeco is what is used as the decorator. That is why you need makeDeco to return the function you want to use as the decorator.
Post a Comment for "How To Create A Decorator Function With Arguments On Python Class?"