裝飾器模式:
程式設計裝飾器是一種設計模式,可在運行時為現有物件或函式添加新的行為或功能,而無需改變其核心結構。這是透過使用提供新增功能的裝飾器物件或函數「包裝」原始物件或函數來實現的。裝飾器模式對於靈活擴展行為、促進程式碼重複使用以及遵守開放-封閉原則等原則非常有用。
在 Python 中,裝飾器是修改或擴展函數或方法行為的靈活方式,而無需更改其實際程式碼。
def decorator(func):
def wrapper():
print("Before calling the function.")
func()
print("After calling the function.")
return wrapper
@decorator # Applying the decorator to a function
def greet():
print("Hello, World!")
greet()