Python教程:assert、isinstance的用法
阿新 • • 發佈:2020-12-15
1.assert
函式說明:
assert語句是一種插入除錯斷點到程式的一種便捷的方式。
使用範例
assert 3 == 3 assert 1 == True assert (4 == 4) print('-----------') assert (3 == 4) ''' 丟擲AssertionError異常,後面程式不執行 ''' print('-----------') 輸出結果: assert (3 == 4) AssertionError 可以看到只輸出一個-----------,後面的由於assert (3 == 4)丟擲異常而不執行。
2.isinstance
函式說明 :
當我們定義一個class的時候,我們實際上就定義了一種資料型別。我們定義的資料型別和Python自帶的資料型別,比如str、list、dict沒什麼兩樣:
判斷一個變數是否是某個型別可以用isinstance()判斷:
'''
遇到問題沒人解答?小編建立了一個Python學習交流QQ群:778463939
尋找有志同道合的小夥伴,互幫互助,群裡還有不錯的視訊學習教程和PDF電子書!
'''
class Student():
def __init__(self, name, score):
self.name = name
self. score = score
a = '10'
b = 3c = [1, 2, 3]
d = (1, 2, 3)
f = Student('Eden', 99.9)
print(isinstance(a, str)) # True
print(isinstance(b, int)) # True
print(isinstance(c, list)) # True
print(isinstance(d, tuple)) # True
print(isinstance(f, Student)) # True