使用循环来装饰Python中的多个导入函数

Mad*_*ist 6 python decorator python-decorators

我是Python和装饰者的新手,所以如果这似乎是一个微不足道的问题,请道歉.

我正在尝试使用Python中的循环将装饰器应用于多个导入的函数,如下所示

from random import random, randint, choice

def our_decorator(func):
    def function_wrapper(*args, **kwargs):
        print("Before calling " + func.__name__)
        res = func(*args, **kwargs)
        print(res)
        print("After calling " + func.__name__)
    return function_wrapper

for f in [random, randint, choice]:
    f = our_decorator(f)

random()
randint(3, 8)
choice([4, 5, 6])
Run Code Online (Sandbox Code Playgroud)

理想情况下,我希望输出采用以下形式:

Before calling random
<random_value>
After calling random
Before calling randint
<random_integer>
After calling randint
Before calling choice
<random_choice>
After calling choice
Run Code Online (Sandbox Code Playgroud)

但是,我只将选择函数的结果作为输出.

<random_choice among 4,5 6>
Run Code Online (Sandbox Code Playgroud)

装饰器还没有应用于任何函数,它看起来像random()和randint(3,8)调用没有被执行.

我想知道,这里出了什么问题以及如何使用循环来装饰多个导入的函数?

谢谢您的帮助

Rem*_*ich 5

您正在装饰功能,然后依次将名称绑定f到每个功能.所以在循环之后,f将等于最后一个装饰函数.原始功能的原始名称不受影响.

你必须使用这些名字,比如

gl = globals()
for f_name in ['random', 'randint', 'choice']:
    gl[f_name] = our_decorator(gl[f_name])
Run Code Online (Sandbox Code Playgroud)

但我倾向于手动将装饰器依次应用于每个函数.