python程序的执行顺序_Python方法中的执行顺序
參見英文答案 >
Assigning to variable from parent function: “Local variable referenced before assignment”????????????????????????????????????5個(gè)
我試過看幾個(gè)不同的例子,但我不確定為什么這不起作用.說我有一些像這樣的代碼:
def loadVariable():
global count
count = 0
def loadDictionary():
location = 'some location'
global myDict
myDict = pickle.load(open(location, 'rb'))
def main():
loadVariable()
loadDictionary()
for item in myDict:
if item.startswith("rt"):
count += 1
item = item[3:]
if __name__ == '__main__':
main()
在我看來,if語句被執(zhí)行,它啟動(dòng)了main()方法.然后,加載全局變量,加載字典并執(zhí)行for循環(huán).
但是,當(dāng)我運(yùn)行代碼時(shí),我被告知在分配之前引用了局部變量count.為什么會(huì)這樣?
編輯(解釋我在評(píng)論中寫的一些內(nèi)容):
這不起作用(雖然我認(rèn)為這是因?yàn)槿衷谶@里使用錯(cuò)誤):
global count
def loadVariables()
count = 0
def main():
loadVariables()
rest of code etc
這也不起作用:
def loadVariables()
count = 0
def main():
global count
loadVariables()
rest of code etc
到目前為止我唯一可以使用它的方法是使用上面提供的鏈接,即將計(jì)數(shù)視為列表,如下所示:
def loadVariables():
global count
count = [0]
def main():
loadVariables():
rest of code etc
count[0] += 1
總結(jié)
以上是生活随笔為你收集整理的python程序的执行顺序_Python方法中的执行顺序的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中与label类似的控件是_
- 下一篇: 中国一共有几艘航母?