欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

深入淺析Python獲取對象信息的函數(shù)type()、isinstance()、dir()

 更新時間:2018年09月17日 11:39:18   作者:zgcr654321  
這篇文章主要介紹了Python獲取對象信息的函數(shù)type()、isinstance()、dir()的相關(guān)知識,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下

type()函數(shù):

使用type()函數(shù)可以判斷對象的類型,如果一個變量指向了函數(shù)或類,也可以用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")

輸出結(jié)果為True。

如果要判斷一個對象是否是函數(shù)怎么辦?

我們可以使用types模塊中定義的常量。types模塊中提供了四個常量types.FunctionType、types.BuiltinFunctionType、types.LambdaType、types.GeneratorType,分別代表函數(shù)、內(nèi)建函數(shù)、匿名函數(shù)、生成器類型。

import types
def fn():
 pass
print(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()函數(shù):

對于有繼承關(guān)系的類,我們要判斷該類的類型,可以使用isinstance()函數(shù)。

如:

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)))

運行截圖如下:

一般情況下,在判斷時,我們優(yōu)先使用isinstance()判斷類型。

dir()函數(shù):

如果要獲得一個對象的所有屬性和方法,可以使用dir()函數(shù),它返回一個包含字符串的list。

如,獲得一個str對象的所有屬性和方法:

print(dir('abc'))

運行結(jié)果:

['__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中,如果你調(diào)用len()函數(shù)試圖獲取一個對象的長度,實際上,在len()函數(shù)內(nèi)部,它自動去調(diào)用該對象的__len__()方法,因此下面的代碼是等價的:

print(len('abc'))
print('abc'.__len__())

運行截圖如下:

我們也可以給自己定義的類寫一個__len__()方法。

如:

class MyDog(object):
 def __len__(self):
 return 100
dog1 = MyDog()
print(len(dog1))

運行截圖如下:

前后沒有__的都是普通屬性或方法。

我們還可以使用getattr()函數(shù)獲取屬性,setattr()函數(shù)設(shè)置屬性,hasattr()函數(shù)查找是否具有某屬性。

如:

class MyObject(object):
 def __init__(self):
 self.x = 9
 def power(self):
 return self.x * self.x
obj1 = MyObject()
print(hasattr(obj1, 'x'))
print(hasattr(obj1, 'y'))
setattr(obj1, 'y', 19)
print(hasattr(obj1, 'y'))
print(getattr(obj1, 'y'))

運行截圖如下:

如果試圖獲取不存在的屬性,會拋出AttributeError的錯誤。我們可以傳入一個default參數(shù),如果屬性不存在,就返回默認值。

getattr()函數(shù)、setattr()函數(shù)、hasattr()函數(shù)也可以用于獲得、設(shè)置、查找對象的方法。

如:

class MyObject(object):
 def __init__(self):
 self.x = 9

 def power(self):
 return self.x * self.x
obj1 = MyObject()
print(hasattr(obj1, 'power'))
print(getattr(obj1, 'power'))
fn = getattr(obj1, 'power')
print(fn())

運行截圖如下:

可以看到調(diào)用fn()的結(jié)果與調(diào)用obj1.power()的結(jié)果是一樣的。

總結(jié):

通過內(nèi)置的一系列函數(shù),我們可以對任意一個Python對象進行剖析,拿到其內(nèi)部的數(shù)據(jù)。

要注意的是,只有在不知道對象信息的時候,我們才會去獲取對象信息。

如:

def readImage(fp):
 if hasattr(fp, 'read'):
  return readData(fp)
 return None

假設(shè)我們希望從文件流fp中讀取圖像,我們首先要判斷該fp對象是否存在read方法,如果存在,則該對象是一個流,如果不存在,則無法讀取。這樣hasattr()就派上了用場。

在Python這類動態(tài)語言中,根據(jù)鴨子類型,有read()方法,不代表該fp對象就是一個文件流,它也可能是網(wǎng)絡(luò)流,也可能是內(nèi)存中的一個字節(jié)流,但只要read()方法返回的是有效的圖像數(shù)據(jù),就不影響讀取圖像的功能。

以上所述是小編給大家介紹的Python獲取對象信息的函數(shù)type()、isinstance()、dir(),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論