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

本文探讨了Python中跨文件引用变量时遇到的NameError,并提供了解决方案。建议通过传递变量作为参数来增强模块间的独立性,避免直接依赖另一个模块内部的状态。

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值