一、type()函数

判断基本数据类型可以直接写intstr等:

 >>> class Animal(object):
... pass
...
>>> type(123)
<class 'int'>
>>> type('')
<class 'str'>
>>> type(None)
<class 'NoneType'>
>>> type(abs)
<class 'builtin_function_or_method'>
>>> type(Animal())
<class '__main__.Animal'>
 >>> type(123) == type(456)
True
>>> type(123) == int
True

判断一个对象是否是函数:

 >>> import types
>>> def fn():
... pass
...
>>> type(fn)==types.FunctionType
True
>>> type(abs)==types.BuiltinFunctionType
True
>>> type(lambda x: x)==types.LambdaType
True
>>> type((x for x in range(10)))==types.GeneratorType
True

二、isinstance()函数

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

 >>> class Animal(object):
... pass
...
>>> class Dog(Animal):
... pass
...
>>> d = Dog()
>>> isinstance(d, Dog)
True
>>> isinstance(d, Animal)
True

用isinstance()判断基本类型:

 >>> isinstance('a', str)
True
>>> isinstance(123, int)
True
>>> isinstance(b'a', bytes)
True

并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:

 >>> isinstance([1, 2, 3], (list, tuple))
True
>>> isinstance((1, 2, 3), (list, tuple))
True

优先使用isinstance()判断类型,可以将指定类型及其子类“一网打尽”。

三、dir()函数

如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:

>>> dir('abc')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

列表中类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:

 >>> len('abc')
3
>>> 'abc'.__len__()
3

自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法:

 >>> class MyDog(object):
... def __len__(self):
... return 100
...
>>> dog = MyDog()
>>> len(dog)
100

列表中剩下的都是普通属性或方法,比如lower()返回小写的字符串:

 >>> 'abc'.upper()
'ABC'

四、getattr()setattr()以及hasattr()

测试该对象的属性:

 >>> class MyObject(object):
... def __init__(self):
... self.x = 9
... def power(self):
... return self.x * self.x
...
>>> obj = MyObject()
>>> hasattr(obj, 'x')
True
>>> hasattr(obj, 'y')
False
>>>
>>> setattr(obj, 'y', 20)
>>> hasattr(obj, 'y')
True
>>> getattr(obj, 'y')
20
>>> getattr(obj, 'z')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyObject' object has no attribute 'z'
>>> getattr(obj, 'z', 100) # 指定默认值
100

测试该对象的方法:

 >>> hasattr(obj, 'power')
True
>>> getattr(obj, 'power')
<bound method MyObject.power of <__main__.MyObject object at 0x1014be400>>
>>> fn = getattr(obj, 'power')
>>> fn
<bound method MyObject.power of <__main__.MyObject object at 0x1014be400>>
>>> fn()
81

python 面向对象五 获取对象信息 type isinstance getattr setattr hasattr的更多相关文章

  1. Python面向对象:获取对象信息

    学习笔记内容简介: 获取对象属性和方法的函数: type(): 判断对象类型 isinstance() : 判断class的类型 dir() : 获得一个对象的所有属性和方法 把属性和方法列出来是不够 ...

  2. python遍历并获取对象属性--dir(),__dict__,getattr,setattr

    一.遍历对象的属性: 1.dir(obj) :返回对象的所以属性名称字符串列表(包括属性和方法). for attr in dir(obj): print(attr) 2.obj.__dict__:返 ...

  3. Python快速学习-获取对象信息

    1type() 获取对象的基本类型,判断两个对象类型. 2types 判断对象是否是函数,使用前要引入import types 3isinstance() 判断class类型,判断一个变量是否是某种类 ...

  4. Python面向对象-获取对象信息type()、isinstance()、dir()

    type() type()函数用于判断对象类型: >>> type(11) <class 'int'> >>> type('abc') <clas ...

  5. Python实用笔记 (21)面向对象编程——获取对象信息

    当我们拿到一个对象的引用时,如何知道这个对象是什么类型.有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type()判断: >>> ...

  6. Python基础(获取对象信息)

    import types print(type('abc') == str)#True print(type(123) == int)#True def f1(): pass print(type(f ...

  7. Python面向对象 -- 继承和多态、获取对象信息、实例属性和类属性

    继承和多态 继承的好处: 1,子类可以使用父类的全部功能 2,多态:当子类和父类都存在相同的方法时,子类的方法会覆盖父类的方法,即调用时会调用子类的方法.这就是继承的另一个好处:多态. 多态: 调用方 ...

  8. python 面向对象编程、获取对象信息

    面向对象与面向过程 参考链接:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0 ...

  9. python基础——获取对象信息

    python基础——获取对象信息 当我们拿到一个对象的引用时,如何知道这个对象是什么类型.有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type( ...

随机推荐

  1. 前端学习之-- JavaScript

    JavaScript笔记 参考:http://www.cnblogs.com/wupeiqi/articles/5602773.html javaScript是一门独立的语言,游览器都具有js解释器 ...

  2. 关于用String Calender类 计算闰年的Demo

    package cn.zmh.zuoye; import java.util.Calendar; public class StringRun { public static void main(St ...

  3. vs npm设置淘宝npm

    VS2017自带的npm会去国外的镜像下载文件, 奇慢无比, 还是马云家淘宝的镜像适合国内用户. 淘宝npm镜像地址:  https://registry.npm.taobao.org VS中使用淘宝 ...

  4. weblogic线程阻塞性能调优(图解)

    转自:http://blog.csdn.net/z69183787/article/details/12647539 声明:出现这个问题有程序方面.网络方面.weblogic设置方面等等原因,此文章主 ...

  5. pip命令自动补全功能;设置代理;使用国内源

    这是pip自带的功能 执行的脚本 把脚本写入.zshrc或者profile等里面,执行source立即生效 设置代理: pip --proxy=http://username:password@pro ...

  6. Reload file in vim

    68down voteaccepted Give this a try: :e From :h :e: Edit the current file. This is useful to re-edit ...

  7. Deepin-我为什么推荐它!

    针对Win上的开发软件,大部分都需要密匙或者破解,而Deepin不敢说一应俱全,但全沾边是没问题的 无论是编程.娱乐还是其它的,基本上都可以做到,而且它还应用了Crossover来兼容大部分的Win软 ...

  8. FZU 2150 Fire Game (暴力BFS)

    [题目链接]click here~~ [题目大意]: 两个熊孩子要把一个正方形上的草都给烧掉,他俩同一时候放火烧.烧第一块的时候是不花时间的.每一块着火的都能够在下一秒烧向上下左右四块#代表草地,.代 ...

  9. Eclipse:Some sites could not be found. See the error log for more detail.解决的方法

    今天遇到了一个奇葩的问题.我把我的sdk tools的版本号升级到23后.我在eclipse中尝试升级ADT,发现了这么一个问题,以下分析下原因: 当我在eclipse中选择Help-->Che ...

  10. Linux 简单的Shell输出

    echo:用于输出指定字符串或用于在Shell中打印Shell变量的值    语法格式:echo [选项] [参数]    -n:不输出换行 linlin@ubuntu:~/linlin/text$ ...