Python 3,全局变量,模块
如何将此代码移动到模块中的函数? 我有全局变量“last_msg”和“fake”。我尝试在函数中使用“global”表示“last_msg”,但它超出了范围,因为函数在模块中,而“last_msg”在主范围中Python 3,全局变量,模块,python,python-3.x,module,global,Python,Python 3.x,Module,Global,如何将此代码移动到模块中的函数? 我有全局变量“last_msg”和“fake”。我尝试在函数中使用“global”表示“last_msg”,但它超出了范围,因为函数在模块中,而“last_msg”在主范围中 main.py from module import Timeout last_msg = {'Foo': 0} name = 'Foo' fake = False timeout = 3 fake = Timeout(fake, name, timeout) >> N
main.py
from module import Timeout
last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3
fake = Timeout(fake, name, timeout)
>> NameError: name 'last_msg' is not defined
看来我做到了
main.py
from module import Timeout
last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3
fake, last_msg = Timeout(fake, name, last_msg, timeout)
这里有一些关于如何访问全局以及python如何处理全局的信息。为此,代码将为:
module.py
def Timeout(fake, name, timeout):
import main
if not fake:
if name not in main.last_msg:
main.last_msg[name] = 0
if main.last_msg[name] > 0:
main.last_msg[name] -= 1
fake = True
else:
main.last_msg[name] = timeout
else:
if name in main.last_msg:
main.last_msg[name] = 0
return fake
而main.py
将如下所示:
last_msg = {'Foo': 0}
from module import Timeout
# last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3
fake = Timeout(fake, name, timeout)
您的代码不足以让我们说出问题所在。您的示例中没有
import
,也没有回溯。我现在更新了它。您好,作为SO社区的一部分,我们的目标通常是鼓励学习,并为下一个遇到此类问题的程序员提供资源。虽然这可能是有效的代码,可能是好的设计,也可能不是好的设计,但这两个目标都无法实现。相反,你可以做的是解释模块化代码实践或提供见解。如果你做了你想做的事,这是最好的。
module.py
def Timeout(fake, name, timeout):
import main
if not fake:
if name not in main.last_msg:
main.last_msg[name] = 0
if main.last_msg[name] > 0:
main.last_msg[name] -= 1
fake = True
else:
main.last_msg[name] = timeout
else:
if name in main.last_msg:
main.last_msg[name] = 0
return fake
last_msg = {'Foo': 0}
from module import Timeout
# last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3
fake = Timeout(fake, name, timeout)