简体   繁体   English

Python:更改也是参数的全局变量的函数

[英]Python: function to alter a global variable that is also parameter

def fxn(L):
    """ 
    """
    global L = 2

L = 1
fxn(L)
print(L)

I have a function like the one above. 我有类似上面的功能。 Assume I need the function to alter the global variable from within the function so that when I print L after calling fxn(L). 假设我需要从函数内部更改全局变量的函数,以便当我在调用fxn(L)之后打印L时。 I end up with the 2 rather than 1. 我最终得到2而不是1。

Is there any way to do this? 有什么办法吗? I cant use global L in the function because L is also a parameter. 我不能在函数中使用全局L,因为L也是一个参数。

You should not use the same variable as global variable and the functional argument to the function using that global variable. 您不应该使用与全局变量相同的变量以及使用该全局变量的函数的函数参数。

But since you have asked, you can do it using the globals() and locals() . 但是,既然您已经提出要求,您就可以使用globals()locals()来做到这一点。 Below is the sample code: 下面是示例代码:

>>> x = 5
>>> def var_test(x):
...     print('GLOBAL x: ', globals()['x'])
...     print('LOCAL x: ', locals()['x'])
...     globals()['x'] = 111
...     print('GLOBAL x: ', globals()['x'])
...     print('LOCAL x: ', locals()['x'])
...
>>> var_test(20)
GLOBAL x:  5
LOCAL x:  20
GLOBAL x:  111
LOCAL x:  20

This is a bad idea, but there are ways, for example: 这是一个坏主意,但是有很多方法,例如:

a = 5

def f(a):
    def change_a(value):
        global a
        a = value
    change_a(7)

f(0)

print(a)   # prints 7

In reality, there is seldom any need for writing to global variables. 实际上,几乎不需要写入全局变量。 And then there is little chance that the global has the same name as a variable which just cannot change the name. 而且,全局变量与变量相同的名称的可能性很小,后者不能更改名称。

If you are in such a situation, ask yourself "am i using global too often?" 如果您处于这种情况,请问自己“我是否经常使用global变量?”

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

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