Is it possible to make one decorator which I could apply for classes and methods?
Example:
@my_dec(1)
class MyClass(object):
@my_dec(2)
def my_method(self):
# something here
assert MyClass._x == 1
assert MyCLass.my_method._x == 2
Is it possible to make one decorator which I could apply for classes and methods?
Example:
@my_dec(1)
class MyClass(object):
@my_dec(2)
def my_method(self):
# something here
assert MyClass._x == 1
assert MyCLass.my_method._x == 2
Yes, it is possible. Basically you need to create a function that accepts the value 1 or 2 and then returns the actual decorator to which the function or class object is later passed on, now inside the decorator we can use setattr
to set the attribute on the class or function object.
def my_dec(x):
# Here x is going to be the argument passed to my_dec, i.e 1 or 2
def decorator(func_or_cls):
setattr(func_or_cls, '_x', x)
return func_or_cls
return decorator
@my_dec(1)
class MyClass(object):
@my_dec(2)
def my_method(self):
pass
assert MyClass._x == 1
assert MyClass.my_method._x == 2
To understand how decorators work, do read this great answer: How can I make a chain of function decorators in Python?