In the project, we will validate the parameter type passed by the client on each interface, and return to the client "parameter error" error code if the validation does not pass.
This not only facilitates debugging, but also increases robustness. Because the client can cheat, do not easily believe that the client passed over the parameters.
Validation types are useful with the type function, such as
>>type (' foo ') = = str
True
>>type (2.3) in (int,float)
True
Now that you have type () to judge the types, why are there isinstance ()?
One obvious difference is in judging subclasses.
Type () does not consider a subclass to be a parent class type.
Isinstance () considers a subclass to be a parent class type.
Thousand words is inferior to one yard.
Class Foo (object): Pass class Bar (foo): pass print type (foo ()) = = Fooprint Type (Bar ()) = = Fooprint Isinstance (Bar (), foo) class Foo (object): Pass class Bar (foo): pass print type (foo ()) = = Fooprint type (bar ()) = = Fooprint Isinstance (bar (), Foo) output truefalsetrue
It is important to note that the old class is not the same as the type () result of the new class. The old class is 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:< C9/>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 ()) output old style class old
style class
New Style class
True
There is no saying isinstance is better than type. Only one is better suited to demand.