[英]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.