在模块之间共享全局变量

时间:2020-04-25 19:04:17

标签: python

我有2个python模块。其中之一是一个布尔变量,该变量不断变化(根据输入)。
在第二个模块中,我根据第一个模块中的boolean变量的值进行操作。

我希望同时更新此共享变量,但自第一次导入以来,该值不变。
我试图使用全局变量,但这也行不通!

以一种简化的方式:

module1.py:

my_boolean = True
while True:
    a = input()
    if a == 'change':
        my_boolean = not my_boolean

在module2.py中:

import module1
while True:
    print (module1.my_boolean)

#The output of print is constant and is not real-time.

共享此变量及其更新值的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

您可以使用生成器功能执行此操作。生成器是一个特殊的函数,它不执行调用即返回一个迭代器,该迭代器将执行主体,直到出现yield语句为止。任何带有yield语句的函数都是生成器。

module1.py:

# This function will not execute until the for loop requests a value.
def getBools():
    my_boolean = True
    while True:
        a = input()
        if a == 'change':
            my_boolean = not my_boolean
        # Pause execution and hand this value to the for loop.
        yield my_boolean

module2.py:

import module1

for b in module1.getBools():
    print(b)

答案 1 :(得分:0)

以下作品-也许可以帮助您

模块4:

my_boolean = True

模块1:

import module4

def change_value():
    a = input()
    if a == 'change':
        module4.my_boolean = not module4.my_boolean

模块2:

import module4

def print_current_value():
    print (module4.my_boolean)

#The output of print is constant and is not real-time.

模块3:

from module1 import change_value
from module2 import print_current_value

while True:
    print_current_value()
    change_value()

运行模块3显示模块正在共享模块4的变量。

True
change
False
change
True
asdf
True
asdf
True
相关问题