简体   繁体   English

将全局变量分配给函数的局部变量

[英]Assign global variable to a function's local variable

I want to loop over some global variable i and each time compile a new function that uses the instantaneous value of i . 我想遍历一些全局变量i ,每次编译一个使用i瞬时值的新函数。 I can then use each of these functions in future, independent of the current value of i . 然后,我将来可以独立于i的当前值使用这些函数中的每一个。

The problem is I can't find a good way to make the global variable i stay local within the namespace of the function. 问题是我不能找到一个很好的方法,使全局变量i留在函数的命名空间内的局部。 For example: 例如:

i = 0

def f():
    return i

i = 1

print(f()) #Prints 1, when I want 0

I found one solution but it seems very clumsy: 我找到了一种解决方案,但看起来很笨拙:

i = 0

def g(x):
    def h():
        return x
    return h

f = g(i)
i = 1

print(f()) #Prints 0 as I wanted.

Is there a better way to do this, maybe some kind of decorator? 有没有更好的方法来执行此操作,也许是某种装饰器?

Python functions are objects, you can set an attribute on them: Python函数是对象,您可以在它们上设置属性:

i = 0

def f():
    return f.i

f.i = i

i = 1

print(f()) # Prints 0 as you wanted

or: 要么:

for i in range(5):
    f.i = i
    print(f())

Note that an argument would do the same. 请注意,参数将执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM