參考自廖雪峰的Python教程
Python自省-------在運行時能夠獲得對象的類型
- type()尖奔,判斷對象類型
- dir()钳垮, 帶參數(shù)時獲得該對象的所有屬性和方法马昨;不帶參數(shù)時把曼,返回當前范圍內(nèi)的變量胡岔、方法和定義的類型列表
- isinstance()椿息,判斷對象是否是已知類型
- hasattr()歹袁,判斷對象是否包含對應(yīng)屬性
- getattr(),獲取對象屬性
- setattr()寝优, 設(shè)置對象屬性
1条舔、type()
type()返回對應(yīng)的class類型
In [27]: type(123)
Out[27]: int
In [28]: type('123')
Out[28]: str
In [29]: type(None)
Out[29]: NoneType
2、dir()
不帶參數(shù)
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
帶參數(shù)
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', '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']
這里看下len()
len()函數(shù)返回字符長度
>>> len('ABC')
3
在len()函數(shù)內(nèi)部乏矾,它自動去調(diào)用該對象的__len__()方法
>>> 'ABC'.__len__()
3
看個函數(shù)
In [34]: class Mydog(object):
...: def __len__(self):
...: return 100
...:
In [35]: mydog = Mydog()
In [36]: len(mydog)
Out[36]: 100
3孟抗、isinstance()
判斷a數(shù)據(jù)類型是不是list
In [37]: a = [1, 2, 3]
In [38]: isinstance(a, list)
Out[38]: True
getattr迁杨、hasattr、setattr獲取對象的狀態(tài)
In [1]: class Myobject(object):
...: def __init__(self):
...: self.x = 9
...: def power(self):
...: return self.x * self.x
...:
In [2]: obj = Myobject()
In [3]: obj.power()
Out[3]: 81
In [4]: hasattr(obj, 'x') # 有屬性x么凄硼?
Out[4]: True
In [5]: hasattr(obj, 'y') # 有屬性y么铅协?
Out[5]: False
In [6]: setattr(obj, 'y') # 設(shè)置屬性必須有三個參數(shù),少了值
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-3b0a0f22117d> in <module>()
----> 1 setattr(obj, 'y')
TypeError: setattr expected 3 arguments, got 2
In [7]: setattr(obj, 'y', 100) # 設(shè)置屬性y的值為100
In [8]: hasattr(obj, 'y') # 有屬性y么摊沉?
Out[8]: True
In [9]: getattr(obj, 'y') # 獲取屬性y狐史!
Out[9]: 100
In [10]: obj.y # 獲取屬性y
Out[10]: 100
In [11]: obj.x # 獲取屬性x
Out[11]: 9
獲取不存在的屬性,會拋出AttributeError
In [12]: getattr(obj, 'z')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-95c3c0ec4e01> in <module>()
----> 1 getattr(obj, 'z')
AttributeError: 'Myobject' object has no attribute 'z'
可以傳入一個默認參數(shù)说墨,不存在就拋出默認參數(shù)
In [13]: getattr(obj, 'z', 404)
Out[13]: 404