
獸人,金幣,布爾…… 看這么多次都膩了,最起碼我們得把他們簡化一點,
簡介
使用 與 (AND) 運算子時,如果第一個條件 (在 AND 左邊那個) 為假,第二個條件 (右邊那個) 永遠不會執行,
你可以好好利用這點!
這些代碼有可能出錯:
enemy = hero.findNearestEnemy() # 如果 enemy 為 None,那么 AND 就是 False # 所以 enemy.type 不會執行,避開了錯誤, if enemy and enemy.type == "munchkin": hero.attack(enemy)下面帶有與運算子的代碼不會有這個問題:
enemy = hero.findNearestEnemy() # 如果 enemy 為 None,獲取 enemy.type 時會出錯! if enemy.type == "munchkin": hero.attack(enemy)默認代碼
# 打敗食人魔,收集金幣,一切都那么平常, # 使用 與(AND) 在同一行檢查存在性和型別, while True: enemy = hero.findNearestEnemy() # 有了與(AND),只在敵人存在時檢查型別 if enemy and enemy.type == "munchkin": hero.attack(enemy) # 尋找最近的物品# 如果有名為 “coin” (金幣)的物品存在,那就快去收集它!
概覽
與 (AND) 運算子具有短路求值 (short-circuit evaluation) 特性,
這句話的意思是,如果在 and 前面的運算式為 假 (或者 null), 那么在運算子后面的運算式不執行或不求值,
我們可以應用到物件屬性的讀取中,尤其是不確定物件是否存在的情況下, 比如,我們想讀取敵人的型別,首先我們得確保那個敵人存在,否則會得到一個錯誤:
enemy = hero.findNearestEnemy() if enemy: if enemy.type == "burl": ## 做點啥But we can make it shorter:
enemy = hero.findNearestEnemy() if enemy and enemy.type == "burl": ## 做點啥我們不需要擔心敵人不存在的參考錯誤 (reference error),因為這種情況下第二部分不會執行
平常的一天 解法
# 打敗食人魔,收集金幣,一切都那么平常, # 使用 與(AND) 在同一行檢查存在性和型別, while True: enemy = hero.findNearestEnemy() # 有了與(AND),只在敵人存在時檢查型別 if enemy and enemy.type == "munchkin": hero.attack(enemy) # 尋找最近的物品 item = hero.findNearestItem() # 如果有名為 “coin” (金幣)的物品存在,那就快去收集它! if item and item.type == "coin": hero.moveXY(item.pos.x, item.pos.y) 本攻略發于極客戰記官方教學欄目,原文地址為: https://codecombat.163.com/news/jikezhanji-senlinpingchangdeyitian 極客戰記——學編程,用玩的!轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/184122.html
標籤:Python
下一篇:2020Python練習一
