gpt4 book ai didi

Python 3、全局变量、模块

转载 作者:行者123 更新时间:2023-11-30 22:12:35 25 4
gpt4 key购买 nike

如何将此代码移至模块中的函数?我有全局变量“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)

>> NameError: name 'last_msg' is not defined

<>

module.py

def Timeout(fake, name, timeout):
global last_msg

if not fake:
if name not in last_msg:
last_msg[name] = 0

if last_msg[name] > 0:
last_msg[name] -= 1
fake = True
else:
last_msg[name] = timeout
else:
if name in last_msg:
last_msg[name] = 0

return fake

最佳答案

这个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 看起来像这样:

last_msg = {'Foo': 0}
from module import Timeout

# last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3

fake = Timeout(fake, name, timeout)

关于Python 3、全局变量、模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51052025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com