2015-05-05 172 views
0

我見過人們經常推薦使用isinstance()而不是type(),我發現它很奇怪,因爲type()對我來說似乎更易讀。爲什麼使用isinstance()而不是type()?

>>> isinstance("String",str) 
True 
>>> type("String") is str 
True 

後者似乎更Python和清晰而前者稍模糊,並暗示特定的用途,我(例如,測試用戶創建的類,而不是內建類型),但那裏,我一些其他的好處米不知道? type()是否會導致一些不穩定的行爲或錯過一些比較?

+0

記得文檔解釋爲什麼要使用'isinstance'。我需要時間去尋找。 –

+1

如果你想知道更多,'polymorphish'是一個關鍵字。 –

+2

請注意,最Pythonic的方法是把它看作*如果*是一個字符串(或更一般的東西,例如一個序列),並且(可選)從錯誤中恢復。我偶爾使用'isinstance(whatever,basestr)',我需要*將字符串與其他序列區分開來,但是否則它有什麼關係? – jonrsharpe

回答

6

讓我給你舉個簡單的例子,爲什麼他們可以是不同的:

>>> class A(object): pass 
>>> class B(A) : pass 
>>> a = A() 
>>> b = B() 

到目前爲止,聲明的變量AA衍生變量B

>>> isinstance(a, A) 
True 
>>> type(a) == A 
True 

>>> isinstance(b, A) 
True 
>>> type(b) == A 
False 
1

您不能在此處使用子類。

爲什麼限制自己只有一個類型,當一個子類將滿足接口?如果有人想要使用class mystr(str): ...做某件事,那麼你的代碼仍然可以工作,並且不需要知道使用了子類的

因此,使用isinstance()是更pythonic的方法;你的代碼應該尋找支持的行爲,而不是特定的類型。

1

爲Python 2.x的基本例如:標準字符串和Unicode字符串,用共同的基類basestring

s = "123" 
u = u"123" 
isinstance(s, str) is True 
type(u) == str # something which has string nature returns False for this test 
# these tests are common-pattern in Python 2.x and behaves correctly 
isinstance(s, basestring) is True 
isinstance(u, basestring) is True 
1

這裏是反例:

class A(): 
    pass 

a = A() 

>>> isinstance(a, A) 
True 
>>> type(a) is A 
False 

因此我認爲isinstance爲一個更通用的。

+0

請注意,這隻會發生,如果'A'是一箇舊式的類;使用新式類(3.x中的所有類,2.x中從'object'繼承的類)'類型(a)是A'。 – jonrsharpe

相關問題