将全局值作为参数传递给装饰器和函数

时间:2017-02-17 01:12:19

标签: python arguments global decorator

我是python和学习装饰的新手。具有NO参数和WITH参数(作为字符串)的装饰器似乎是直截了当的。但是,如果我想传递一个全局值而不是'srting'作为参数,它就会失败。我所有这些都是不同的文件,所以我想使用全局变量。

File1:
def decorator(arg1, arg2):
    def real_decorator(function):
        def wrapper(*args):
            print "i am decorated"
            print arg1, arg2
            function(*args)
        return wrapper
    return real_decorator

File2:
def glob(a, b):
    global arg1
    arg1 = a
    global arg2
    arg2 = b

@decorator(arg1, arg2) # pass it as 'string' ie('arg1', 'arg2') it PASSES, pass it as i have showed, it FAILS
def print_args(*args):
    print 'i am ordinary'
    for arg in args:
        print arg

File3:
#calling functions
glob(1, 2)
print_args(3,4,5)
======================================
Pass: (when given as string)
i am decorated
arg1 arg2
i am ordinary
3
4
5
======================================
Fail: (when given global var)
Traceback (most recent call last):
 File "/User/File2.py", line 19, in <module>
@decorator(arg1, arg2)
NameError: global name 'arg1' is not defined

对此的任何帮助都非常感谢。我从昨天开始就坚持这个...... !!

1 个答案:

答案 0 :(得分:2)

您应该在零缩进级别声明arg1arg2,即作为模块内的全局变量:

arg1 = None
arg2 = None

def decorator(arg1, arg2):
    def real_decorator(function):
        def wrapper(*args):
            print("i am decorated")
            print(arg1, arg2)
            function(*args)
        return wrapper
    return real_decorator

def glob(a, b):
    global arg1
    arg1 = a
    global arg2
    arg2 = b

glob(1, 2)

#calling functions
@decorator(arg1, arg2) # pass it as 'string' ie('arg1', 'arg2') it PASSES, pass it as i have showed, it FAILS
def print_args(*args):
    print('i am ordinary')
    for arg in args:
        print(arg)


print_args(3,4,5)

此外,请务必在传递glob(1, 2)arg1之前致电arg2作为装饰者的参数。