Python:用于更改也是参数的全局变量的函数 [英] Python: function to alter a global variable that is also parameter

查看:67
本文介绍了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?"

这篇关于Python:用于更改也是参数的全局变量的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆