您可以将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")