def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper def say_hello(): print("Hello!") # Apply the decorator decorated_say_hello = my_decorator(say_hello) decorated_say_hello()
Something is happening before the function is called. Hello! Something is happening after the function is called.
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()
Something is happening before the function is called. Hello! Something is happening after the function is called.
class MyClass: @staticmethod def static_method(): print("This is a static method.") @classmethod def class_method(cls): print(f"This is a class method of {cls}.") # Usage MyClass.static_method() MyClass.class_method()
This is a static method. This is a class method of <class '__main__.MyClass'>.
class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, value): if value < 0: raise ValueError("Radius cannot be negative.") self._radius = value # Usage c = Circle(5) print(c.radius) c.radius = 10 print(c.radius)
5 10
import time def timer(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Function '{func.__name__}' took {end_time - start_time:.4f} seconds to execute.") return result return wrapper @timer def slow_function(seconds): time.sleep(seconds) return "Done sleeping!" # Usage print(slow_function(2))
Function 'slow_function' took 2.0027 seconds to execute. Done sleeping!
def decorator1(func): def wrapper(): print("Decorator 1") func() return wrapper def decorator2(func): def wrapper(): print("Decorator 2") func() return wrapper @decorator1 @decorator2 def say_hello(): print("Hello!") say_hello()
Decorator 1 Decorator 2 Hello!