• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
皎陽
博客园    首页    新随笔    联系   管理    订阅  订阅

python 判断数据类型及释疑

Python 判断数据类型有type和isinstance

基本区别在于:

type():不会认为子类是父类

isinstance():会认为子类是父类类型

class Color(object):
pass

class Red(Color):
pass

print type(Color()) == Color
print type(Red()) == Color
print isinstance(Red(),Color)
执行结果如下:

True
False
True

用isinstance判断mongDB中的一些数据类型:

字符串、int、long、float - isinstance(data, (int, str, types.LongType, float))
时间类型 - isinstance(data, datetime.datetime)
布尔类型 - isinstance(data, (bool))
字典类型 - isinstance(data, (dict))
数组 - isinstance(data, (list))
unicode - isinstance(data, unicode)
mongo obJect - isinstance(data, bson.objectid.ObjectId)

可以引入types模板,获取数据类型:

inport types

types取值:

  BooleanType
  BufferType
  BuiltinFunctionType
  BuiltinMethodType
  ClassType
  CodeType
  ComplexType
  DictProxyType
  DictType
  DictionaryType
  EllipsisType
  FileType
  FloatType
  FrameType
  FunctionType
  GeneratorType
  GetSetDescriptorType
  InstanceType
  IntType
  LambdaType
  ListType
  LongType
  MemberDescriptorType
  MethodType
  ModuleType
  NoneType
  NotImplementedType
  ObjectType
  SliceType
  StringType
  StringTypes
  TracebackType
  TupleType
  TypeType
  UnboundMethodType
  UnicodeType
  XRangeType

python 2 实例:

import types
type(x) is types.IntType # 判断是否int 类型
type(x) is types.StringType #是否string类型

还可以:

import types
type(x) == types(1) # 判断是否int 类型
type(x) == type('a') #是否string类型

python 3 实例:

if type(fileJson) is dict:
if type(fileJson) == dict:
if type(fileJson) == type({}):

 

posted @ 2019-06-10 17:57  皎陽  阅读(1669)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3