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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值