Python:我如何在模块中使用主文件中的变量? [英] Python: How can I use variable from main file in module?

查看:530
本文介绍了Python:我如何在模块中使用主文件中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个文件main.py和irc.py.

main.py

  import irc 
var = 1
func()

irc.py

  def func():
print var

当我尝试运行main.py时,出现这个错误:

lockquote
NameError:global name'var'没有定义


如何使它成功?

@编辑

我认为有一个更好的解决方案,但不幸的是,我发现的唯一一个是创建另一个文件并将其导入到这两个文件

main.py

 导入irc 
导入另一个
another.var = 1
irc.func()

irc.py

  import another 
def func():
print another.var

另一个.py

  var = 0 


解决方案

Don吨。通过它。尽量保持代码尽可能分离:一个模块不应该依赖另一个模块的内部工作。相反,尝试尽可能少地暴露。通过这种方式,您可以保护自己不必每次改变世界时,都会让事情有所不同。



main.py >

  import irc 
var = 1
func(var)

irc.py

  def func(var):
print var


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:我如何在模块中使用主文件中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆