python - 在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
模块有必要吗?有没有更好的办法”?
解决方案
也许您可以编写某种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
推荐阅读
- c# - 展平复杂的对象层次结构,以便我可以在 WPF 中将数据绑定到它
- swift - ARKit – 如何检测场景视图中特定特征点的颜色?
- java - 嵌套类中阴影的所有可能性
- arrays - Java's equivalent of Javascript's array.sort([compareFunction])?
- python - Build Python with static openssl
- sql - repeat loop in Sql?
- android - 无法解析 EditText 上的 setselection()
- javascript - 单击链接时如何突出显示一行
- java - 一次防止“24”小时值(没有秒)
- nginx - 忽略一组 IP 地址的特定规则