Mastering Python Decorators: A Complete Guide
Mastering Python Decorators: A Complete Guide ๐
Decorators wrap functions or classes to extend behavior without modifying original code, boosting reusability and readability.
1. Basic Function Decorator
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}")
say_hello("Chulsoo")
2. Decorator with Arguments
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet():
print("Hello")
greet() # Prints "Hello" 3 times
3. Class Decorator
def add_repr(cls):
cls.__repr__ = lambda self: f"<{cls.__name__} {self.__dict__}>"
return cls
@add_repr
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Chulsoo", 30)
print(p) # <Person {'name': 'Chulsoo', 'age': 30}>
Summary
- Decorators extend functionality by wrapping code.
- @ syntax applies them cleanly.
- Various use cases for function and class decorators exist.
Comments
Post a Comment