首页 > 解决方案 > 在python的辅助prgm中修改主prgm变量的正确方法

问题描述

我似乎找不到正确的方法来做到这一点。我有一个带有变量的主模块x和一个必须能够更新的辅助模块x

以下不起作用:

#main.py
import aux
x=0
aux.update()

#aux.py
import main
def update():
   main.x += 1

third持有一个模块似乎是可能的x

#main.py
import aux,third
third.x = 0
aux.update()

#aux.py
import third
def update():
   third.x += 1

#third.py
x = 0

这个third模块有必要吗?有没有更好的办法”?

标签: pythonglobal-variables

解决方案


也许您可以编写某种class,创建它的实例并将其传递给您的update()函数:

#main.py
import aux

class Foo:
    def __init__(self, x):
    self.x = x

third = Foo(0)
print(third.x)
aux.update(third)
print(third.x)


#aux.py
def update(instance):
   instance.x += 1

输出:

0
1

推荐阅读