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( ...
随机推荐
- Speculative store buffer
A speculative store buffer is speculatively updated in response to speculative store memory operatio ...
- Shell脚本的编写,sed的使用以及一些正则表达式
Shell脚本的简单编写以及sed的使用 标签(空格分隔): 博客文章 前一阵子为了批量修改Web审计规则,故编写了一个Shell脚本,顺便使用了下sed,顺便把正则表达式也重新学习一遍,感觉还是需要 ...
- 通过调用C语言的库函数与在C代码中使用内联汇编两种方式来使用同一个系统调用来分析系统调用的工作机制
通过调用C语言的库函数与在C代码中使用内联汇编两种方式来使用同一个系统调用来分析系统调用的工作机制 前言说明 本篇为网易云课堂Linux内核分析课程的第四周作业,我将通过调用C语言的库函数与在C代码中 ...
- 【小记事】解除端口占用(Windows)
开发中有时会因为端口占用而导致起项目时报错(如下图),这时候只要解除端口占用即可. 解除端口占用: 1.打开cmd(win+r),查看端口占用情况 netstat -ano | findstr 端口号 ...
- Spring4MVC 请求参数映射和Content-type
目录 前言 不使用注解(不传则为null) 基本数据类型和日期类型 自定义类型POJO @PathVariable注解 @RequestParam 注解 @RequestBody注解 复杂对象Arra ...
- Knockout.js用jquery的val设置值不更新
用如下方法,加上change() .val("blah").change()
- 运维平台之CMDB系统建设
CMDB是运维的基础核心系统,所有的元数据和共享数据管理源,类似于业务中的账号平台的作用.本篇文章,我将从概念篇.模型篇.到实现与实施篇具体的进行阐述. CMDB也称配置管理,配置管理一直被认为是 I ...
- Ulua_toLua_基本案例(一)
Ulua_toLua_基本案例 在Untiy中用Lua.必需要LuaInterface.LuaInterface的介绍请看:点击打开链接 能够先光写Lua,生成.lua的纯文件.再Unity中通过,l ...
- [LeetCode][Java] Subsets
题目: Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset ...
- LightOj 1027 A Dangerous Maze【概率】
题目链接:http://www.lightoj.com/volume_showproblem.php? problem=1027 题意: 你面前有n个门,每一个相应一个数字,若为正xi.代表xi分钟后 ...