1

由于如果在函数中对变量名称进行了赋值,则变量名称被声明为本地变量,并且我想从函数中访问模块变量,我可以在模块中导入模块名称,然后使用它来访问模块变量吗?

示例(文件名:server.py):

import server

bar = 5

def foo():
   server.bar = 10
4

4 回答 4

6

Instead of using the global statement, as suggested in all of the other answers, don't use module level variables, but a class as a container or else another module just for the globals:

# mg.py

bar = 5

# server.py
import mg

def foo():
    mg.bar = 10

or

class mg:
    bar = 5

def foo():
    mg.bar = 10

This way you don't need to put global statements everywhere, you can re-use those names, and it's clear which bar you're referring to.

Edit: Also, it is possible to import a module inside itself, but you can't change variables in the main module that way. So this would work:

# selfimport.py
import selfimport

def foo():
    print selfimport.foo

bar = 3

if __name__ == '__main__':
    print selfimport.bar
    foo()

But this wouldn't:

# selfimport.py
import selfimport

bar = 3

def foo():
    selfimport.bar = 5

if __name__ == '__main__':
    print selfimport.bar
    foo()
    print bar # bar is still 3!

If you're only using the globals as constants, you wouldn't need the global statement anyway. You also need to make sure to wrap code you only want to execute in the main module in an if statement as above, or you'll recurse.

于 2011-08-17T07:18:57.360 回答
1

Why not:

def foo():
  global bar
  bar = 10
于 2011-08-17T07:16:44.007 回答
1

你不能像那样导入它,你也不需要。直接使用模块全局变量即可。

def foo():
    global bar
    bar = 10

您需要将其声明为全局的,以便对其进行设置,而不是创建局部变量。

于 2011-08-17T07:16:34.710 回答
0

no, instead use the global statement:

def foo():
    global bar
    bar = 10
于 2011-08-17T07:18:26.103 回答