- 判斷是否是某種類型的實(shí)例:isinstance()方法
- 可以用 type() 函數(shù)獲取變量的類型,它返回一個(gè) Type 對(duì)象
>>> type(123)
<type 'int'>
>>> s = Student('Bob', 'Male', 88)
>>> type(s)
<class '__main__.Student'>
- 可以用 dir() 函數(shù)獲取變量的所有屬性
>>> dir(123) # 整數(shù)也有很多屬性...
['__abs__', '__add__', '__and__', '__class__', '__cmp__', ...]
- getattr() 和 setattr( )函數(shù)
>>> s = Student('Bob', 'Male', 88)
>>> getattr(s, 'name') # 獲取name屬性
'Bob'
>>> setattr(s, 'name', 'Adam') # 設(shè)置新的name屬性
>>> s.name
'Adam'
>>> getattr(s, 'age') # 獲取age屬性躁倒,但是屬性不存在叨襟,報(bào)錯(cuò):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'age'
>>> getattr(s, 'age', 20) # 獲取age屬性,如果屬性不存在柄延,就返回默認(rèn)值20:
20
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者