Sobes.tech
Junior — Middle

Can you explain what a decorator for a class method in Python is?

sobes.tech AI

Answer from AI

A decorator for class methods in Python is a function that takes a class method and returns a modified version of that method. It allows adding additional behavior to a method without changing its original code.

For example, a decorator can be used for logging method calls, access rights checks, or caching results.

Here's a simple example of a decorator for a class method:

class MyClass:
    def decorator(func):
        def wrapper(self, *args, **kwargs):
            print(f"Calling method {func.__name__}")
            return func(self, *args, **kwargs)
        return wrapper

    @decorator
    def method(self, x):
        return x * 2

obj = MyClass()
print(obj.method(5))  # Outputs a message and the result 10

Here, @decorator wraps the method, adding extra output when called.

Can you explain what a decorator for a class method… - sobes.tech