裝飾功能

裝飾器增強了其他功能或方法的行為。任何將函式作為引數並返回增強函式的函式都可以用作裝飾器

# This simplest decorator does nothing to the function being decorated. Such
# minimal decorators can occasionally be used as a kind of code markers.
def super_secret_function(f):
    return f

@super_secret_function
def my_function():
    print("This is my secret function.")

@-notation 是句法糖,相當於以下內容:

my_function = super_secret_function(my_function)

為了理解裝飾器的工作原理,記住這一點很重要。這個 unsugared 語法清楚地說明了為什麼裝飾器函式將函式作為引數,以及為什麼它應該返回另一個函式。它還演示瞭如果返回函式會發生什麼 :

def disabled(f):
    """
    This function returns nothing, and hence removes the decorated function
    from the local scope.
    """
    pass

@disabled
def my_function():
    print("This function can no longer be called...")

my_function()
# TypeError: 'NoneType' object is not callable

因此,我們通常在裝飾器中定義一個新函式並返回它。這個新函式首先要做它需要做的事情,然後呼叫原始函式,最後處理返回值。考慮這個簡單的裝飾器函式,它列印原始函式接收的引數,然後呼叫它。

#This is the decorator
def print_args(func):
    def inner_func(*args, **kwargs):
        print(args)
        print(kwargs)
        return func(*args, **kwargs) #Call the original function with its arguments.
    return inner_func

@print_args
def multiply(num_a, num_b):
    return num_a * num_b
  
print(multiply(3, 5))
#Output:
# (3,5) - This is actually the 'args' that the function receives.
# {} - This is the 'kwargs', empty because we didn't specify keyword arguments.
# 15 - The result of the function.