您的位置:首页 > 编程语言 > Python开发

Python的type 还是要靠isinstance判断类型

2015-10-12 23:17 911 查看
今天处理数据库内容迁移,碰到时间数据类型无法使用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: