python中的assert命令通常在代碼除錯中會被使用,它用來判斷緊跟著的代碼的正確性,如果滿足條件(正確),萬事大吉,程式自動向后執行,如果不滿足條件(錯誤),會中斷當前程式并產生一個AssertionError錯誤, 它近似等同于如下代碼:
if __debug__:
if not expression: raise AssertionError
比如我們計算一個實際問題,我們經歷了一系列的計算后得到了一個時間t值,這時我們就可以在代碼中使用assert t >= 0來對我們獲取到的時間t進行測驗,如果t < 0,則與實際問題矛盾,這時就會產生一個AssertionError,我們就可以知道是我們的計算出現了問題,我們就可以回過頭去修改前面的計算程序而不用再繼續往下看了,可以讓我們分段來檢查自己書寫的代碼,
為了更好的了解assert的用法,請看如下代碼:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
assert x > 5
print(f"the value of x is: {x}")
if __name__ == "__main__":
main = Debug()
main.mainProgram()
"""
當我們輸入6時,會列印出x的結果6
result:
Please input a integer: 6
the value of x is: 6
當我們輸入5時,會被告知assert x > 5有問題,并且中斷程式執行,產生AssertionError錯誤,
result:
assert x > 5
AssertionError
"""
上述代碼完全等同于下面的代碼:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
if x > 5:
print(f"the value of x is: {x}")
else:
raise AssertionError
if __name__ == "__main__":
main = Debug()
main.mainProgram()
然而這樣的assert報錯提示并不完美,因為只是告知了assert x>5這一行出現錯誤,并沒有文字性的錯誤提示,如果assert的內容比較復雜時,我們很可能會一時半會不知道錯誤的具體原因,這時我們應該采用assert的拓展提示功能,拓展功能等同于代碼:
if __?debug__:
if not <expression1>: raise AssertionError, <expression2>
具體例子代碼如下:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
assert x > 5, "the value of x should greater than 5"
print(f"the value of x is: {x}")
if __name__ == "__main__":
main = Debug()
main.mainProgram()
"""
我們輸入5,代碼會標注出錯誤的行,以及我們設定的錯誤提示資訊
result:
assert x > 5, "the value of x should greater than 5"
AssertionError: the value of x should greater than 5
"""
至此,assert的用法就基本結束了,但是我自己又探索了一下這個錯誤提示文字的運行機制,代碼如下:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
assert x > 5, x <= 5
print(f"the value of x is: {x}")
if __name__ == "__main__":
main = Debug()
main.mainProgram()
"""
我們輸入5,
result:
assert x > 5, x <= 5
AssertionError: True
"""
可以看到我們將assert后面本應該出現的文字提示部分改為了一個運算式x <= 5,這時的輸出結果為AssertionError: True,我們輸入5的時候assert x > 5不符合條件,因此會報錯并且輸出后面我們添加的錯誤提示資訊,但是現在的錯誤提示資訊是一個運算式,5 <= 5,運算式正確,運算式的結果應為True,結合我們上一個給出的字串的錯誤提示,我們可以推斷,這個我們附加的錯誤提示其實相當于執行了一個print()函式,在這個例子中,print(x < =5)的結果就會在螢屏上列印一個True,即上述代碼等同于:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
if x > 5:
print(f"the value of x is: {x}")
else:
print(x <= 5)
if __name__ == "__main__":
main = Debug()
main.mainProgram()
如果大家覺得有用,請高抬貴手給一個贊讓我上推薦讓更多的人看到吧~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/100830.html
標籤:其他
下一篇:python 實作自動訪問網頁
