Python3类和实例之获取对象信息

  当我们拿到一个对象的引用时,如何知道这个对象是什么类型,有哪些方法呢

  使用type()

  判断对象类型使用type()函数

  基本类型都可以用type()判断

<class 'int'>
>>> type('123')
<class 'str'>
>>> type(None)
<class 'NoneType'>
>>> type(())
<class 'tuple'>
>>> type({})
<class 'dict'>
>>> type([])
<class 'list'>

  如果一个变量指向函数或者类也可以用type()判断

>>> type(abs)
<class 'builtin_function_or_method'>
>>> type(Animal())
<class '__main__.Animal'>

  type()函数返回的是什么类型,它返回对应的Class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同

>>> type(123)==type(345)
True
>>> type(123)==int
True
>>> type('123')==str
True
>>> type(123)==type('123')
False

  判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量

>>> 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()判断

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

  并且还可以判断一个变量是否某些类型中的一种,例如

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

  

  使用dir()

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

>>> 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__()方法,所以,下面的代码是等价的

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

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

>>> 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(),我们可以直接操作一个对象的状态:

>>> 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错误

>>> getattr(obj,'z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyObject' object has no attribute 'z

  可以传入一个default参数,如果属性不存在,就返回默认值,获取'z'属性,如果不存在就返回404

>>> getattr(obj,'z',404)
404

  也可以获取对象的方法

#有属性'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对象进行剖析,拿到其内部的数据。要注意的是,只有在不知道对象信息的时候,我们才会去获取对象信息。如果可以直接写:

sum=obj.x+obj.y

  就不要写

sum=getattr(obj,'x')+getattr(obj,'y')

  

  

  

原文地址:https://www.cnblogs.com/minseo/p/11096211.html