eup*_*a83 1 python scope python-module
如果变量名称在函数内有赋值给它们,并且我想从函数中访问模块变量,那么我可以在模块中导入模块名称然后用它来访问模块变量吗?
示例(文件名:server.py):
import server
bar = 5
def foo():
server.bar = 10
Run Code Online (Sandbox Code Playgroud)
而不是global像所有其他答案中所建议的那样使用语句,不要使用模块级变量,而是使用类作为容器,或者仅使用全局变量的另一个模块:
# mg.py
bar = 5
# server.py
import mg
def foo():
mg.bar = 10
Run Code Online (Sandbox Code Playgroud)
要么
class mg:
bar = 5
def foo():
mg.bar = 10
Run Code Online (Sandbox Code Playgroud)
这样你就不需要在global任何地方放置语句,你可以重复使用这些名称,并且很清楚bar你指的是哪个.
编辑:此外,可以在自身内部导入模块,但不能以这种方式更改主模块中的变量.这样可行:
# selfimport.py
import selfimport
def foo():
print selfimport.foo
bar = 3
if __name__ == '__main__':
print selfimport.bar
foo()
Run Code Online (Sandbox Code Playgroud)
但这不会:
# selfimport.py
import selfimport
bar = 3
def foo():
selfimport.bar = 5
if __name__ == '__main__':
print selfimport.bar
foo()
print bar # bar is still 3!
Run Code Online (Sandbox Code Playgroud)
如果你只使用全局变量作为常量,那么你无论如何都不需要global语句.您还需要确保在if上面的语句中包装您只想在主模块中执行的代码,否则您将会递归.
| 归档时间: |
|
| 查看次数: |
1249 次 |
| 最近记录: |