I have 2 files main.py and irc.py.
main.py
import irc
var = 1
func()
irc.py
def func():
print var
When I try to run main.py I'm getting this error
NameError: global name 'var' is not defined
How to make it work?
@Edit
I thought there is a better solution but unfortunately the only one i found is to make another file and import it to both files
main.py
import irc
import another
another.var = 1
irc.func()
irc.py
import another
def func():
print another.var
another.py
var = 0
解决方案
Don't. Pass it in. Try and keep your code as decoupled as possible: one module should not rely on the inner workings of the other. Instead, try and expose as little as possible. In this way, you'll protect yourself from having to change the world every time you want to make things behave a little different.
main.py
import irc
var = 1
func(var)
irc.py
def func(var):
print var
本文探讨了Python中跨文件引用变量时遇到的NameError,并提供了解决方案。建议通过传递变量作为参数来增强模块间的独立性,避免直接依赖另一个模块内部的状态。
191

被折叠的 条评论
为什么被折叠?



