[英]Python 3, Global Variables, Modules
如何将此代码移动到模块中的函数? 我有全局变量'last_msg'和'假'。 我试图在我的函数中使用'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
这个链接有一些关于如何访问全局变量以及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)
好像我已经做到了。
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)
<>
module.py
def Timeout(fake, name, last_msg, timeout):
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, last_msg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.