Why use isinstance() instead of type()?
This question already has an answer here:
Let me give you a simple example why they can be different:
>>> class A(object): pass
>>> class B(A) : pass
>>> a = A()
>>> b = B()
So far, declared a variable A
and a variable B
derived from A
.
>>> isinstance(a, A)
True
>>> type(a) == A
True
BUT
>>> isinstance(b, A)
True
>>> type(b) == A
False
You are precluding the possibility to use subclasses here.
Why limit yourself to just the one type when a subclass would satisfy the interface? If someone wants to use class mystr(str): ...
for something, your code would still work and doesn't need to know that a subclass was used.
As such, using isinstance()
is the more pythonic approach; your code should look for supported behaviours, not specific types.
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
链接地址: http://www.djcxy.com/p/54220.html