Sobes.tech
Junior — Middle

Kas teab, mis on dekorator klassi meetoditele Pythonis?

sobes.tech AI

Vastus AI-lt

Decorators for class methods in Python are functions that take a class method and return a modified version of that method. They allow adding additional behavior to the method without changing its source code.

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

An example of a simple 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))  # Will print a message and the result 10

Here, @decorator wraps the method, adding extra output during the call.