Modifying global variable with same name as local

2020-01-31 00:51发布

Suppose I have a global variable a. And within a function definition, we also have a local variable named a. Is there any way to assign the value of the global variable to that of the local variable?

a = 'foo'

def my_func(a = 'bar'):
    # how to set global a to value of the local a?

4条回答
够拽才男人
2楼-- · 2020-01-31 01:28
>>> a = 'foo'
>>> def my_func(a='bar'):
...     return globals()['a']
...
>>> my_func()
'foo'
查看更多
你好瞎i
3楼-- · 2020-01-31 01:34

Let python know that you want the global version;

def my_func():
    global a
    a = 'bar'
查看更多
在下西门庆
4楼-- · 2020-01-31 01:38

Use built-in function globals().

globals()

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

a = 'foo'

def my_func(a = 'bar'):
    globals()['a'] = a

BTW, it's worth mentioning that a global is only "global" within the scope of a module.

查看更多
祖国的老花朵
5楼-- · 2020-01-31 01:41

Don't muddle global and local namespaces to begin with. Always try and use a local variable versus a global one when possible. If you must share variables between scopes you can still pass the variables without need for a global placeholder. Local variables are also referenced much more efficiently accessed than globals.

A few links:

Sharing Variables in Python

Variable performance

查看更多
登录 后发表回答