简体   繁体   中英

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

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

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() . 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?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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