[英]Inner function in python doesn't return at the right place
在我的內部函數的以下代碼中,無論分數如何,返回的唯一值都是(0, None)
。 我可以看到for
循環在團隊達到勝利或憐憫閾值時終止,但這並不能作為整個函數的返回值。 我不記得像這樣工作的 return 語句,所以有人可以解釋為什么會發生這種情況嗎?
def victory_check() -> Tuple[Optional[int], Optional[Team]]:
scores_all_bad: bool = True
for team in tea_lst:
print(team.score) # debug
if team.score >= victory_threshold:
return 1, team
if team.score < mercy_rule:
return -1, team
if team.score > bad_ai_end:
scores_all_bad = False
if scores_all_bad:
return -1, None
return 0, None
Team
對象由以下內容構成。 測試工具將 -12 到 14 之間的隨機整數添加到每個團隊的分數上,以假裝玩一手牌。 Team.score
值正確反映在打印語句中。
class Team:
players: List[Player]
score: int = 0
bid: int
def __init__(self, players: List[Player]):
self.players = players
不確定您的team_list
是什么樣的。 假設它是一個字典列表,此代碼按預期工作。
team_lst = [{'score': 40}]
def victory_check():
scores_all_bad: bool = True
for team in team_lst:
print(team.keys())
print(team.get('score')) # debug
if team.get('score') >= 5:
return 1, team
if team.get('score') < 5:
return -1, team
if team.get('score') > 100:
scores_all_bad = False
if scores_all_bad:
return -1, None
return 0, None
根據文檔,
return 以表達式列表(或 None)作為返回值離開當前函數調用。
因此,函數執行(不返回)多個返回語句的唯一方法是當您在 finally 塊中運行帶有參數的 try-except 塊時。 像下面這樣的東西。 需要明確的是,(Python 內部執行了兩個返回,但實際上只有一個返回)
def nums(list_ofvals):
score = True
try:
for v in list_ofvals:
if v == 1:
return "one return", 1
elif v == 3:
return "three return", 3
except:
pass
finally:
if score == True:
return "true score"
else:
pass
print(nums([1])) #function call
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.