python 面向对象五 获取对象信息 type isinstance getattr setattr hasattr
一、type()函数
判断基本数据类型可以直接写int
,str
等:
>>> 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的更多相关文章
- Python面向对象:获取对象信息
学习笔记内容简介: 获取对象属性和方法的函数: type(): 判断对象类型 isinstance() : 判断class的类型 dir() : 获得一个对象的所有属性和方法 把属性和方法列出来是不够 ...
- python遍历并获取对象属性--dir(),__dict__,getattr,setattr
一.遍历对象的属性: 1.dir(obj) :返回对象的所以属性名称字符串列表(包括属性和方法). for attr in dir(obj): print(attr) 2.obj.__dict__:返 ...
- Python快速学习-获取对象信息
1type() 获取对象的基本类型,判断两个对象类型. 2types 判断对象是否是函数,使用前要引入import types 3isinstance() 判断class类型,判断一个变量是否是某种类 ...
- Python面向对象-获取对象信息type()、isinstance()、dir()
type() type()函数用于判断对象类型: >>> type(11) <class 'int'> >>> type('abc') <clas ...
- Python实用笔记 (21)面向对象编程——获取对象信息
当我们拿到一个对象的引用时,如何知道这个对象是什么类型.有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type()判断: >>> ...
- Python基础(获取对象信息)
import types print(type('abc') == str)#True print(type(123) == int)#True def f1(): pass print(type(f ...
- Python面向对象 -- 继承和多态、获取对象信息、实例属性和类属性
继承和多态 继承的好处: 1,子类可以使用父类的全部功能 2,多态:当子类和父类都存在相同的方法时,子类的方法会覆盖父类的方法,即调用时会调用子类的方法.这就是继承的另一个好处:多态. 多态: 调用方 ...
- python 面向对象编程、获取对象信息
面向对象与面向过程 参考链接:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0 ...
- python基础——获取对象信息
python基础——获取对象信息 当我们拿到一个对象的引用时,如何知道这个对象是什么类型.有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type( ...
随机推荐
- HDU 1896 【留个使用priority_queue容器的样例】
感谢<啊哈!算法>的讲解,水鸟弄懂了什么是优先队列. 题意是:在路上有很多石子,给出他们的初始位置和小明能够将他们扔出的距离,当小明遇到奇数个石子的时候就会把它扔出,遇到偶数个就会忽略他, ...
- java基础 4 继承(3)this 与 super关键字
this用来指向当前实例对象,用来区别成员变量与方法的形参 super可以用来访问父类的方法或成员变量,当子类构造函数需要显示的调用父类的构造函数时,super()必须为构造函数中的第一条语句.
- Simics 破解 转
http://www.eetop.cn/blog/html/28/1066428-type-bbs-view-myfav.html http://blog.sina.com.cn/s/blog_538 ...
- Import Items – Validation Multiple Languages Description
ð 提交标准请求创建和更新物料,因语言环境与处理次序方式等因素,造成物料中英(更多语言)描述和长描述混乱刷新. 症状: >>> Submit Standard Open Inter ...
- [Angular] Write Compound Components with Angular’s ContentChild
Allow the user to control the view of the toggle component. Break the toggle component up into multi ...
- hdu 5303 Delicious Apples
这道题贪心 背包 假设在走半圆之内能够装满,那么一定优于绕一圈回到起点.所以我们从中点将这个分开,那么对于每一个区间由于苹果数非常少,所以能够利用pos[x]数组记录每一个苹果所在的苹果树位置,然后将 ...
- NYOJ 158 省赛来了
省赛来了 时间限制:1000 ms | 内存限制:65535 KB 难度: 描写叙述 一年一度的河南省程序设计大赛又要来了. 竞赛是要组队的,组队形式:三人为一队,设队长一名.队员两名. 如今问题 ...
- Java使用三种不同循环结构对1+2+3+...+100 求和
▷//第一种求法,使用while结构 /** * @author 9527 * @since 19/6/20 */ public class Gaosi { public static void ma ...
- 一张图理清js原型链(通过内置对象的引用关系)
很多同学估计写了几年js也没有搞清内置对象之间的原型链关系,鄙人抽空手绘了一张简图,以作参考: 简单说明一下,上图中annonymous()函数相当于是所有函数的根(它本身也是函数),他上面提供了一些 ...
- javascript闭包的应用
我印象中,javascript的闭包属于进阶的范畴,无非是用来在面试中装装逼而已.你看我身边的一个小伙子,有一天我装逼地问他什么是javascript的闭包,他居然连听都没听说过.但他做起前端的东西来 ...