1. 程式人生 > >Python的type 還是要靠isinstance判斷型別

Python的type 還是要靠isinstance判斷型別

今天處理資料庫內容遷移,碰到時間資料型別無法使用type判斷出來的情況

背景知識

datetime模組中的datetime類的例項可以表示一個時刻(日期,以及這個日期中的特定時間),可以不包含時區或者包含時區,並總是忽略閏秒。

import datetime
test = datetime.datetime(2015,10,12,23,0,0)
if test in (int,float,datetime):
    print('ok')
這裡ok打印不出來的,後來測試了下type才知道
>>> type(test)
<type 'datetime.datetime'>
打印不出來是因為datetime是module的型別,壓根不是類,但是type裡面不進行型別檢查,新手很容易犯錯,後來使用了isinstance,程式報錯才發現datetime不行,那個錯誤的程式碼
>>> if isinstance(test,datetime):
...     print('ok')
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

立馬加上類!
>>> if isinstance(test,datetime.datetime):
...     print('ok')
...
ok