Python3,全局变量,模块

2024-05-03 23:58:22 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将此代码移动到模块中的函数? 我有全局变量“last\u msg”和“fake”。我尝试在我的函数中使用'global'作为'last'u msg',但它超出了范围,因为函数在模块中,而'last\u msg'在主作用域中。在

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

<;>

^{pr2}$

Tags: 模块函数namefrompyfoomaintimeout
2条回答

这个link提供了一些关于如何访问全局变量以及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将如下所示:

^{pr2}$

看来我做到了。在

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)

<;>

^{pr2}$

相关问题 更多 >