装饰功能
装饰器增强了其他功能或方法的行为。任何将函数作为参数并返回增强函数的函数都可以用作装饰器。
# 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.