
Decorator 【修飾器】
範例 – 基礎範例
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()
# =========================================================
# Replace the decorator
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!")
decorated_say_hello = my_decorator(say_hello)
decorated_say_hello()帶參數的 Decorators (Decorator factory)
Decorators 應用順序
Syntactic sugar
Last updated