[Python] decorate function and method with same decorator

Discussão em 'Python' iniciado por Stack, Junho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have a function, a class implementing the similar method and a decorator. The current decorator signature does allow it to be used for the function but doesn't work with the method as expected.

    from functools import wraps

    def nice(f):
    @wraps(f)
    def decorator(a, b):
    result = f(a, b)
    return 'result is: %s' % str(result)

    return decorator

    @nice
    def sumup(a, b):
    return a + b


    class Test:
    def __init__(self):
    pass

    @nice
    def sumup(self, a, b):
    return a + b

    print(sumup(2, 6))
    cls = Test()
    print(cls.sumup(4, 8))


    Can I somehow 'overload' decorator? In C++ I would be able to write the same decorator again with the same name but different signature and it would work. Can I use some nice solutions in this case? Or I need to just add the same decorator with different name like:

    def nice_cls(f):
    @wraps(f)
    def decorator(self, a, b):
    result = f(self, a, b)
    return 'result is: %s' % str(result)

    return decorator


    and use it for the method?

    Continue reading...

Compartilhe esta Página