小标
2018-08-09
来源 :
阅读 1287
评论 0
摘要:本文主要向大家介绍了Python语言之python 面向对象五 获取对象信息 type isinstance getattr setattr hasattr,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
本文主要向大家介绍了Python语言之python 面向对象五 获取对象信息 type isinstance getattr setattr hasattr,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
一、type()函数
判断基本数据类型可以直接写int,str等:
1 >>> class Animal(object):
2 ... pass
3 ...
4 >>> type(123)
5
6 >>> type('123')
7
8 >>> type(None)
9
10 >>> type(abs)
11
12 >>> type(Animal())
13
1 >>> type(123) == type(456)
2 True
3 >>> type(123) == int
4 True
判断一个对象是否是函数:
1 >>> import types
2 >>> def fn():
3 ... pass
4 ...
5 >>> type(fn)==types.FunctionType
6 True
7 >>> type(abs)==types.BuiltinFunctionType
8 True
9 >>> type(lambda x: x)==types.LambdaType
10 True
11 >>> type((x for x in range(10)))==types.GeneratorType
12 True
二、isinstance()函数
对于class的继承关系来说,使用type()就很不方便。如果要判断class的类型,可以使用isinstance()函数。
1 >>> class Animal(object):
2 ... pass
3 ...
4 >>> class Dog(Animal):
5 ... pass
6 ...
7 >>> d = Dog()
8 >>> isinstance(d, Dog)
9 True
10 >>> isinstance(d, Animal)
11 True
用isinstance()判断基本类型:
1 >>> isinstance('a', str)
2 True
3 >>> isinstance(123, int)
4 True
5 >>> isinstance(b'a', bytes)
6 True
并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:
1 >>> isinstance([1, 2, 3], (list, tuple))
2 True
3 >>> isinstance((1, 2, 3), (list, tuple))
4 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__()方法,所以,下面的代码是等价的:
1 >>> len('abc')
2 3
3 >>> 'abc'.__len__()
4 3
自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法:
1 >>> class MyDog(object):
2 ... def __len__(self):
3 ... return 100
4 ...
5 >>> dog = MyDog()
6 >>> len(dog)
7 100
列表中剩下的都是普通属性或方法,比如lower()返回小写的字符串:
1 >>> 'abc'.upper()
2 'ABC'
四、getattr()、setattr()以及hasattr()
测试该对象的属性:
1 >>> class MyObject(object):
2 ... def __init__(self):
3 ... self.x = 9
4 ... def power(self):
5 ... return self.x * self.x
6 ...
7 >>> obj = MyObject()
8 >>> hasattr(obj, 'x')
9 True
10 >>> hasattr(obj, 'y')
11 False
12 >>>
13 >>> setattr(obj, 'y', 20)
14 >>> hasattr(obj, 'y')
15 True
16 >>> getattr(obj, 'y')
17 20
18 >>> getattr(obj, 'z')
19 Traceback (most recent call last):
20 File "
21 AttributeError: 'MyObject' object has no attribute 'z'
22 >>> getattr(obj, 'z', 100) # 指定默认值
23 100
测试该对象的方法:
1 >>> hasattr(obj, 'power')
2 True
3 >>> getattr(obj, 'power')
4 <bound method MyObject.power of <__main__.myobject object="" at="" 0x1014be400="">>
5 >>> fn = getattr(obj, 'power')
6 >>> fn
7 <bound method MyObject.power of <__main__.myobject object="" at="" 0x1014be400="">>
8 >>> fn()
9 81
本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号