# selfimport.py
import selfimport
def foo():
print selfimport.foo
bar = 3
if __name__ == '__main__':
print selfimport.bar
foo()
但这不会:
# selfimport.py
import selfimport
bar = 3
def foo():
selfimport.bar = 5
if __name__ == '__main__':
print selfimport.bar
foo()
print bar # bar is still 3!
不要像所有其他答案中建议的那样使用
global
语句,而不要使用模块级变量,而是将类用作容器或其他仅用于全局变量的模块:或者
^{pr2}$这样你就不需要到处放
global
语句,你可以重复使用这些名称,而且很清楚你所指的bar
。在编辑:此外,还可以在模块内部导入模块,但不能通过这种方式更改主模块中的变量。所以这会起作用:
但这不会:
如果只使用全局变量作为常量,那么无论如何也不需要
global
语句。您还需要确保将只想在主模块中执行的代码包装在上面的if
语句中,否则将递归。在为什么不:
你不能那样进口,你也不需要。直接使用module全局变量。在
您需要声明它是全局的,这样就可以设置它,而不是创建一个局部变量。在
相关问题 更多 >
编程相关推荐