Python 之——获取对象信息

Python 之——获取对象信息

1.type():获取变量的数据类型,一般用于基本数据类型

>>> type(123)==type(456)

True

>>> type(123)==int

True

>>> type('abc')==type('123')

True

>>> type('abc')==str

True

>>> type('abc')==type(123)

False

2.isinstance():对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用isinstance()函数

如果继承关系是:

object -> Animal -> Dog -> Husky

创建对象:

>>> a = Animal()

>>> d = Dog()

>>> h = Husky()

使用isinstance判读:

>>> isinstance(h, Dog)

True

>>> isinstance(h, Animal)

True

能用type()判断的基本类型也可以用isinstance()判断:

>>> isinstance('a', str)

True

>>> isinstance(123, int)

True

>>> isinstance(b'a', bytes)

True

3.dir():获得一个对象的所有属性和方法,它返回一个包含字符串的list

如:

dir(11)

['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__p__', '__pmod__', '__doc__', '__float__', '__floorp__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rp__', '__rpmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloorp__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruep__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truep__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

展开阅读全文

页面更新:2024-04-02

标签:对象   能用   字符串   变量   数据类型   函数   属性   类型   关系   方法   数码   信息

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top