• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python 查看数据的类型

武飞扬头像
草明
帮助4

机器学习记录

在 Python 中,有几种方式可以查看一个对象的数据类型:

1. 使用 type()

直接使用 type() 函数可以查看对象的类型:

>>> type(1) 
<class 'int'>
>>> type([])
<class 'list'> 
>>> type(lambda x: x   1) 
<class 'function'>

2. 使用 isinstance()

isinstance() 可以检查一个对象是否为某种类型,或者某个类型的子类:

>>> isinstance(1, int) 
True
>>> isinstance([], list)
True
>>> isinstance(lambda x: x   1, function)  # function 是 type 的别名  
True

3. 检查对象的 __class__ 属性

每个对象都有一个 __class__ 属性指向创建它的类:

>>> 1.__class__ 
<class 'int'>
>>> [].__class__ 
<class 'list'>
>>> (lambda x: x   1).__class__
<class 'function'>

4. 使用 dir()

我们可以使用 dir() 函数获取对象的属性列表,其中通常都包含 __class__ 属性:

>>> dir(1)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

可以看到,1.__class__ 就在这个列表中。

所以 Python 提供了多种方式检查一个对象的类型,包括:

  • type() 函数
  • isinstance() 函数
  • class 属性
  • dir() 函数

可以根据需要选择一种或多种方式来查看对象类型。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfgaihk
系列文章
更多 icon
同类精品
更多 icon
继续加载