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

问题描述:

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

L = 1
fxn(L)
print(L)

我具有类似上面的功能.假设我需要从函数内部更改全局变量的函数,以便当我在调用fxn(L)之后打印L时.我最终得到2而不是1.

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). I end up with the 2 rather than 1.

有没有办法做到这一点?我不能在函数中使用全局L,因为L也是一个参数.

Is there any way to do this? I cant use global L in the function because L is also a parameter.

这是个坏主意,但是有很多方法,例如:

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.

如果您处于这种情况,请问自己我是否经常使用 global ?"

If you are in such a situation, ask yourself "am i using global too often?"