← Back to Python

All Topics

Advertisement

Learn/Python/Intermediate Python

Decorators

Topic: Advanced Functions

Advertisement

Introduction

Decorators modify the behavior of functions or classes without changing their code.

Basic Decorator

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function")
        result = func(*args, **kwargs)
        print("After function")
        return result
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Decorator with Arguments

def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet():
    print("Hi!")

greet()  # Prints "Hi!" 3 times

Built-in Decorators

class MyClass:
    @property
    def value(self):
        return self._value
    
    @staticmethod
    def static_method():
        return "Static"
    
    @classmethod
    def class_method(cls):
        return cls()

Practice Problems

  1. Create timing decorator for functions
  2. Make authentication decorator
  3. Build caching decorator with functools.lru_cache
  4. Create decorator that validates arguments
  5. Implement class method decorator

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →