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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Flask框架来实现将变量值传递到指定的HTML文件。Flask是一个轻量级的Web框架,可以方便地处理HTTP请求和响应。下面是一个简单的示例: 1. 首先,需要安装Flask框架,可以使用pip进行安装: ``` pip install flask ``` 2. 创建一个名为app.py的Python文件,并在其导入Flask模块: ```python from flask import Flask app = Flask(__name__) ``` 3. 定义一个路由,将变量传递给HTML文件: ```python @app.route('/') def index(): name = 'John' return render_template('index.html', name=name) ``` 在上面的代码,我们定义了一个名为index的路由,它会返回一个HTML文件,该文件包含一个名为name的变量变量值为'John'。使用`render_template`函数将变量name传递给HTML文件。 4. 创建一个名为index.html的HTML文件,其可以使用Flask的模板语法来引用Python变量: ```html <!DOCTYPE html> <html> <head> <title>Hello, {{ name }}!</title> </head> <body> <h1>Hello, {{ name }}!</h1> </body> </html> ``` 5. 在app.py文件添加一行代码,用于启动Flask应用程序: ```python if __name__ == '__main__': app.run() ``` 这行代码确保只有在该文件作为程序运行时才会启动Flask应用程序。 6. 在终端运行app.py文件: ``` python app.py ``` 然后,在浏览器访问http://localhost:5000,就可以看到HTML文件变量值已经被成功传递了。 在实际应用,可以使用更复杂的模板语法和更多的路由来构建完整的Web应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值