type()函數:
使用type()函數可以判斷對象的類型,如果一個變量指向了函數或類,也可以用type判斷。
如:
class Student(object): name = 'Student'a = Student()print(type(123))print(type('abc'))print(type(None))print(type(abs))print(type(a))運行截圖如下:
可以看到返回的是對象的類型。
我們可以在if語句中判斷比較兩個變量的type類型是否相同。
如:
class Student(object): name = 'Student'a = Student()if type(123) == type(456): print("True")輸出結果為True。
如果要判斷一個對象是否是函數怎么辦?
我們可以使用types模塊中定義的常量。types模塊中提供了四個常量types.FunctionType、types.BuiltinFunctionType、types.LambdaType、types.GeneratorType,分別代表函數、內建函數、匿名函數、生成器類型。
import typesdef fn(): passprint(type(fn) == types.FunctionType)print(type(abs) == types.BuiltinFunctionType)print(type(lambda x: x) == types.LambdaType)print(type((x for x in range(10))) == types.GeneratorType)
isinstance()函數:
對于有繼承關系的類,我們要判斷該類的類型,可以使用isinstance()函數。
如:
class Animal(object): def run(self): print("動物在跑")class Dog(Animal): def eat(self): print("狗在吃")class Cat(Animal): def run(self): print("貓在跑")dog1 = Dog()cat1 = Cat()print(isinstance(dog1, Dog))print(isinstance(cat1, Cat))print(isinstance(cat1, Animal))print(isinstance(dog1, Animal))運行截圖如下:
可以看到子類的實例不僅是子類的類型,也是繼承的父類的類型。
也就是說,isinstance()判斷的是一個對象是否是該類型本身,或者位于該類型的父繼承鏈上。
能用type()判斷的基本類型也可以用isinstance()判斷,并且還可以判斷一個變量是否是某些類型中的一種。
如:
print(isinstance('a', str))print(isinstance(123, int))print(isinstance(b'a', bytes))print(isinstance([1, 2, 3], (list, tuple)))print(isinstance((1, 2, 3), (list, tuple)))運行截圖如下:
一般情況下,在判斷時,我們優先使用isinstance()判斷類型。
dir()函數:
如果要獲得一個對象的所有屬性和方法,可以使用dir()函數,它返回一個包含字符串的list。
如,獲得一個str對象的所有屬性和方法:
print(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']
類似__xxx__的屬性和方法在Python中都是有特殊用途的。如在Python中,如果你調用len()函數試圖獲取一個對象的長度,實際上,在len()函數內部,它自動去調用該對象的__len__()方法,因此下面的代碼是等價的:
print(len('abc'))print('abc'.__len__())運行截圖如下:
我們也可以給自己定義的類寫一個__len__()方法。
如:
class MyDog(object): def __len__(self): return 100dog1 = MyDog()print(len(dog1))
運行截圖如下:
前后沒有__的都是普通屬性或方法。
我們還可以使用getattr()函數獲取屬性,setattr()函數設置屬性,hasattr()函數查找是否具有某屬性。
如:
class MyObject(object): def __init__(self): self.x = 9 def power(self): return self.x * self.xobj1 = MyObject()print(hasattr(obj1, 'x'))print(hasattr(obj1, 'y'))setattr(obj1, 'y', 19)print(hasattr(obj1, 'y'))print(getattr(obj1, 'y'))
運行截圖如下:
如果試圖獲取不存在的屬性,會拋出AttributeError的錯誤。我們可以傳入一個default參數,如果屬性不存在,就返回默認值。
getattr()函數、setattr()函數、hasattr()函數也可以用于獲得、設置、查找對象的方法。
如:
class MyObject(object): def __init__(self): self.x = 9 def power(self): return self.x * self.xobj1 = MyObject()print(hasattr(obj1, 'power'))print(getattr(obj1, 'power'))fn = getattr(obj1, 'power')print(fn())
運行截圖如下:
可以看到調用fn()的結果與調用obj1.power()的結果是一樣的。
總結:
通過內置的一系列函數,我們可以對任意一個Python對象進行剖析,拿到其內部的數據。
要注意的是,只有在不知道對象信息的時候,我們才會去獲取對象信息。
如:
def readImage(fp): if hasattr(fp, 'read'): return readData(fp) return None
假設我們希望從文件流fp中讀取圖像,我們首先要判斷該fp對象是否存在read方法,如果存在,則該對象是一個流,如果不存在,則無法讀取。這樣hasattr()就派上了用場。
在Python這類動態語言中,根據鴨子類型,有read()方法,不代表該fp對象就是一個文件流,它也可能是網絡流,也可能是內存中的一個字節流,但只要read()方法返回的是有效的圖像數據,就不影響讀取圖像的功能。
以上所述是小編給大家介紹的Python獲取對象信息的函數type()、isinstance()、dir(),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!
新聞熱點
疑難解答