需要一個解決方案或解決方法來從moduleB讀取和寫入moduleA中的變量。下面是代碼:從模塊B讀取和寫入模塊A中的變量
moduleA
import moduleB
variable = 10
def changeVariable():
global variable
variable = 20
def main():
print("From moduleA, variable =", variable, " before change.")
moduleB.main()
print("From moduleA, variable =", variable, " after change.")
if __name__ == "__main__":
main()
moduleB
import moduleA
def main():
print("From moduleB, variable =", moduleA.variable, " before change.")
moduleA.variable = 20 # Try 1
moduleA.changeVariable() # Try 2
print("From moduleB, variable =", moduleA.variable, " after change.")
if __name__ == "__main__":
main()
當運行moduleA我們得到:
- 從moduleA,改變之前變量= 10。
- 從moduleB開始,變化前的變量= 10。
- 從moduleB,變量後變量= 20。
- 來自moduleA,變化後變量= 10。
下面是使用靜態變量另一個例子:
moduleAA
import moduleBB
class AA:
variable = 0
@staticmethod
def changeVariable():
AA.variable = 20
def main():
AA.variable = 10
print("From moduleAA, variable =", AA.variable, " before change.")
moduleBB.main()
print("From moduleAA, variable =", AA.variable, " after change.")
if __name__ == "__main__":
main()
moduleBB
import moduleAA
def main():
print("From moduleB, variable =", moduleAA.AA.variable, " before change.")
moduleAA.AA.variable = 20 # Try 1
moduleAA.AA.changeVariable() # Try 2
print("From moduleB, variable =", moduleAA.AA.variable, " after change.")
if __name__ == "__main__":
main()
當運行moduleAA時,我們得到:
- 從moduleAA,變量= 10之前改變。
- 從moduleBB開始,變化前的變量= 0。
- 從moduleBB,變量後變量= 20。
- 從moduleAA,變化後的變量= 10。
我已經[解釋](https://stackoverflow.com/questions/44550783/change-global-module-variable-from-another-module)你上次發佈這件事發生了什麼。解決方案是停止依賴循環導入,全局變量,特別是跨模塊全局變量依賴項。所有這些事情都會導致脆弱,難以理解的代碼。 – user2357112
@ user2357112非常感謝您的信息。我不明白如何解決這個問題。所以你在說什麼是不可能修改這個變量?我有一個模塊包含一個異步API和另一個包含GUI的模塊。我需要至少有一個字典在兩者之間共享。這本字典應該是靜態的。 – Yster
如何在模塊之間共享數據的問題已經被問到[很多](https://stackoverflow.com/questions/24875798/python-sharing-variables-between-modules),[many](https:// stackoverflow。 com/questions/14247974/python-how-to-share-a-variable-between-two-modules)[times](https://stackoverflow.com/questions/3338283/python-sharing-global-variables-between-模塊和類-文獻)。 (那些剛剛碰巧是我偶然發現的前三個,還有更多。)你甚至嘗試*搜索「python模塊之間的共享變量」嗎? –