Home > Article > Backend Development > The difference between python data type judgment type and isinstance
In the project, we will verify the parameter type passed by the client on each interface. If the verification fails, a "parameter error" error code will be returned to the client.
This not only facilitates debugging, but also increases robustness. Because the client can cheat, don't trust the parameters passed by the client easily.
Verify the type using the type function, which is very easy to use, such as
>>type('foo') == str
True
>>type(2.3) in (int, float)
True
Since there is Type() is used to determine the type, why is there isinstance()?
An obvious difference is in judging subclasses.
type() will not consider the subclass to be a parent class type.
isinstance() will consider the subclass to be a parent class type.
A thousand words are worth a yard.
class Foo(object): pass class Bar(Foo): pass print type(Foo()) == Foo print type(Bar()) == Foo print isinstance(Bar(),Foo) class Foo(object): pass class Bar(Foo): pass print type(Foo()) == Foo print type(Bar()) == Foo print isinstance(Bar(),Foo) 输出 True False True
It should be noted that the type() results of old-style classes and new-style classes are different. Old-style classes are all
class A: pass class B: pass class C(object): pass print 'old style class',type(A()) print 'old style class',type(B()) print 'new style class',type(C()) print type(A()) == type(B()) class A: pass class B: pass class C(object): pass print 'old style class',type(A()) print 'old style class',type(B()) print 'new style class',type(C()) print type(A()) == type(B()) 输出 old style class <type 'instance'> old style class <type 'instance'> new style class <class '__main__.C'> True
There is no saying that isinstance is better than type. Only which one better suits the needs.