May-14-2017, 09:46 AM
May-14-2017, 11:49 AM
from module import function def decorator(func): def wrapper(): # do some stuffs func() # do other stuffs return wrapper any_func = decorator(function) any_func()
May-14-2017, 05:54 PM
Using decorator notation, no. But you can wrap as the previous answer shows.
May-22-2017, 08:05 PM
In case it still isn't quite clear, a decorator is just syntactic sugar around wrapping something with something else, aliasing the original function, if you will. But there's no reason it has to be JUST for functions...
>>> def wrapper(cls): ... class Eggs: ... def __init__(self, other): ... print("pretending to be {0}".format(other)) ... self.other = other() ... def inner(): ... return Eggs(cls) ... return inner ... >>> @wrapper ... class Spam: ... def __init__(self): ... print("SPAM!") ... >>> x = Spam() pretending to be <class '__main__.Spam'> SPAM!I can't actually think of a use for that which wouldn't be better served by just using inheritance, but if such a situation arises, it is possible.