Python:如何在模块中使用主文件中的变量?
我有 2 个文件 main.py 和 irc.py。
main.py
import irc
var = 1
func()
irc.py
def func():
print var
当我尝试运行 main.py 时出现此错误
NameError:全局名称“var”未定义
如何使其工作?
@编辑
我认为有一个更好的解决方案,但不幸的是我发现的唯一一个是创建另一个文件并将其导入到两个文件中
main.py
import irc
import another
another.var = 1
irc.func()
irc.py
import another
def func():
print another.var
another.py
var = 0
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不。将其传递进去。尝试使代码尽可能解耦:一个模块不应依赖于另一个模块的内部工作。相反,尝试尽可能少地暴露。通过这种方式,你可以保护自己,避免每次你想让事情变得有点不同时都必须改变世界。
main.py
irc.py
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
irc.py
嗯,这是我的代码,运行良好:
func.py:
main.py:
Well, that's my code which works fine:
func.py:
main.py:
两个选择。
这将对原始名称的引用复制到导入模块。
这将允许您使用其他模块中的变量,并允许您根据需要更改它。
Two options.
This will copy a reference to the original name to the importing module.
This will let you use the variable from the other module, and allow you to change it if desired.
好吧,函数中的 var 没有声明。您可以将其作为参数传递。
main.py
irc.py
Well, var in the function isn't declared. You could pass it as an argument.
main.py
irc.py
Samir 所说的适用于 Python 2
对于 python 3,你需要这样做。
main.py
irc.py
What Samir said works for Python 2
For python 3 you need to do it this way.
main.py
irc.py