简体   繁体   English

Python:如何在模块中使用主文件中的变量?

[英]Python: How can I use variable from main file in module?

I have 2 files main.py and irc.py.我有 2 个文件 main.py 和 irc.py。
main.py主文件

import irc
var = 1
func()

irc.py irc.py

def func():
    print var

When I try to run main.py I'm getting this error当我尝试运行 main.py 时出现此错误

NameError: global name 'var' is not defined NameError:未定义全局名称“var”

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 irc.py

import another
def func():
    print another.var

another.py另一个.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 main.py

import irc
var = 1
func(var)

irc.py irc.py

def func(var):
    print var

Well, that's my code which works fine: 嗯,这是我的代码工作正常:

func.py: func.py:

import __main__
def func():
    print(__main__.var)

main.py: main.py:

from func import func

var="It works!"
func()
var="Now it changes!"
func()

Two options. 两种选择。

from main import var

def func():
    print var

This will copy a reference to the original name to the importing module. 这会将对原始名称的引用复制到导入模块。

import main

def func():
    print main.var

This will let you use the variable from the other module, and allow you to change it if desired. 这将允许您使用其他模块中的变量,并允许您根据需要进行更改。

Well, var in the function isn't declared. 好吧,没有声明函数中的var。 You could pass it as an argument. 您可以将其作为参数传递。 main.py main.py

import irc
var = 1
func(var)

irc.py irc.py

def func(str):
    print str

What Samir said but it won't work as he wrote it.萨米尔所说的,但在他写的时候不起作用。 It will return 2 errors:它将返回 2 个错误:

*First Error: * NameError: name 'func' is not defined. *第一个错误:* NameError:未定义名称“func”。 You also must import func from irc as shown below.您还必须从 irc 导入 func ,如下所示。

Second Error: SyntaxError: Missing parentheses in call to 'print'.第二个错误: SyntaxError:调用“打印”时缺少括号。 You must put the print var in parenthesis as shown below.您必须将 print var 放在括号中,如下所示。

main.py主文件

import irc
from irc import func

var = 1
func(var)
irc.py

irc.py irc.py

def func(var):
    print(var)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM