在Python中,裝飾器是一種特殊類型的函數,它可以用來修改其他函數的行為。裝飾器本質上是一個接受函數作為參數并返回一個新函數的高階函數。下面是一個簡單的裝飾器示例:
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()
在這個例子中,my_decorator
是一個裝飾器函數,它接受一個函數 func
作為參數,并定義了一個內部函數 wrapper
。wrapper
函數在調用 func
之前和之后分別執行了一些額外的操作。最后,my_decorator
返回了 wrapper
函數。
要使用裝飾器,我們可以在要裝飾的函數定義之前加上一個 @decorator_name
行。在這個例子中,我們在 say_hello
函數定義之前加上了 @my_decorator
,這意味著當我們調用 say_hello
時,實際上是在調用 my_decorator(say_hello)
。
運行上面的代碼,輸出將會是:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
這樣,我們就成功地使用裝飾器修改了 say_hello
函數的行為。