Python中的類不僅可以用來定義對象,還可以用作裝飾器。在Python中,裝飾器是一種Python語言特性,它能把一個函數(shù)改變?yōu)榱硪粋€函數(shù),而不需要改變函數(shù)的原始代碼。
class DecoratorClass: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print("Before the function is called.") self.func(*args, **kwargs) print("After the function is called.") @DecoratorClass def my_function(x, y): print("The function is called.") print(f"x + y = {x+y}")
當我們用@DecoratorClass
這樣的語法來裝飾my_function()
函數(shù)時,DecoratorClass
中的__init__()
函數(shù)將被調(diào)用,并使用my_function()
函數(shù)作為參數(shù)。然后,DecoratorClass
中的__call__()
函數(shù)將被調(diào)用,該函數(shù)將在調(diào)用my_function()
函數(shù)之前和之后打印一條消息。
現(xiàn)在,如果我們調(diào)用my_function()
,我們會得到以下輸出:
Before the function is called. The function is called. x + y = 5 After the function is called.
如您所見,DecoratorClass
將在調(diào)用my_function()
函數(shù)之前和之后打印出"Before the function is called"和"After the function is called"信息。