Python3类和实例之获取对象信息
当我们拿到一个对象的引用时,如何知道这个对象是什么类型,有哪些方法呢
使用type()
判断对象类型使用type()函数
基本类型都可以用type()判断
1 2 3 4 5 6 7 8 9 10 11 | < class 'int' > >>> type ( '123' ) < class 'str' > >>> type ( None ) < class 'NoneType' > >>> type (()) < class 'tuple' > >>> type ({}) < class 'dict' > >>> type ([]) < class 'list' > |
如果一个变量指向函数或者类也可以用type()判断
1 2 3 4 | >>> type ( abs ) < class 'builtin_function_or_method' > >>> type (Animal()) < class '__main__.Animal' > |
type()函数返回的是什么类型,它返回对应的Class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同
1 2 3 4 5 6 7 8 | >>> type ( 123 ) = = type ( 345 ) True >>> type ( 123 ) = = int True >>> type ( '123' ) = = str True >>> type ( 123 ) = = type ( '123' ) False |
判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量
1 2 3 4 5 6 7 8 9 10 11 | >>> 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()
对应calss的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用isinstance()函数
能用type()判断的基本类似也可以用isinstance()判断
1 2 3 4 5 6 | >>> isinstance ( 'a' , str ) True >>> isinstance ( '123' , int ) False >>> isinstance (b 'a' ,bytes) True |
并且还可以判断一个变量是否某些类型中的一种,例如
1 2 3 4 | >>> isinstance ([ 1 , 2 , 3 ],( list , tuple )) True >>> isinstance (( 1 , 2 , 3 ),( list , tuple )) True |
使用dir()
如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获取一个str对象的所有属性和方法
1 2 | >>> dir ( 'ABC' ) [ '__add__' , '__class__' , '__contains__' , '__delattr__' , '__dir__' , '__doc__' , '__eq__' , '__format__' , '__ge__' , '__getattribute__' , '__getitem__' , '__getnewargs__' , '__gt__' , '__hash__' , '__init__' , '__init_subclass__' , '__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' , 'isascii' , '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 2 3 4 | >>> len ( 'ABC' ) 3 >>> 'ABC' .__len__() 3 |
我们自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法:
1 2 3 4 5 6 7 8 9 10 11 | >>> class MyDog( object ): ... def __len__( self ): ... return 100 ... >>> dog = MyDog() >>> dog.__len__ <bound method MyDog.__len__ of <__main__.MyDog object at 0x7fd88ab18cf8 >> >>> dog.__len__() 100 >>> len (dog) 100 |
仅仅把属性和方法列出来是不够的,配合getattr(),setattr()以及hasattr(),我们可以直接操作一个对象的状态:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | >>> class MyObject( object ): ... def __init__( self ): ... self .x = 9 ... def power( self ): ... return self .x * self .x #测试对象属性 >>> obj = MyObject() #有'x'属性吗 >>> hasattr (obj, 'x' ) True #有'y'属性吗 >>> hasattr (obj, 'y' ) False #设置一个'y'属性 >>> setattr (obj, 'y' , 19 ) >>> hasattr (obj, 'y' ) True #获取'y'属性 >>> getattr (obj, 'y' ) 19 |
如果试图获取不存在的属性,会抛出AttributeError错误
1 2 3 4 | >>> getattr (obj, 'z' ) Traceback (most recent call last): File "<stdin>" , line 1 , in <module> AttributeError: 'MyObject' object has no attribute 'z |
可以传入一个default参数,如果属性不存在,就返回默认值,获取'z'属性,如果不存在就返回404
1 2 | >>> getattr (obj, 'z' , 404 ) 404 |
也可以获取对象的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 | #有属性'power'吗 >>> hasattr (obj, 'power' ) True #获取属性'power' >>> getattr (obj, 'power' ) <bound method MyObject.power of <__main__.MyObject object at 0x7fd88ab189e8 >> #获取属性'power'并赋值到变量fn >>> fn = getattr (obj, 'power' ) >>> fn <bound method MyObject.power of <__main__.MyObject object at 0x7fd88ab189e8 >> #调用fn()与调用obj.power()是一样的 >>> fn() 81 |
小结:
通过内置的一系列函数,我们可以对任意一个Python对象进行剖析,拿到其内部的数据。要注意的是,只有在不知道对象信息的时候,我们才会去获取对象信息。如果可以直接写:
1 | sum = obj.x + obj.y |
就不要写
1 | sum = getattr (obj, 'x' ) + getattr (obj, 'y' ) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2018-06-27 Nginx配置认证登录