python跨文件全局变量_在文件之间使用全局变量?

您可以将Python全局变量视为“模块”变量-因此,它们比C中的传统“全局变量”更有用。

全局变量实际上在模块的__dict__并且可以作为模块属性从该模块外部访问。

因此,在您的示例中:# ../myproject/main.py# Define global myList# global myList - there is no "global" declaration at module level. Just inside

# function and methodsmyList = []# Importsimport subfile# Do somethingsubfile.stuff()print(myList[0])

以及:# ../myproject/subfile.py# Save "hey" into myListdef stuff():

# You have to make the module main available for the

# code here.

# Placing the import inside the function body will

# usually avoid import cycles -

# unless you happen to call this function from

# either main or subfile's body (i.e. not from inside a function or method)

import main

main.mylist.append("hey")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值