Python data type judgment type and isinstance difference instance parsing, pythonisinstance
In the project, the parameter type passed by the client is verified on each interface. If the verification fails, the "parameter error" error code is returned to the client.
This not only facilitates debugging, but also increases robustness. Because the client can cheat, do not trust the parameters passed by the client easily.
The type function is used for verification, such
> Type ('foo') = str
True
> Type (2.3) in (int, float)
True
Now that type () is used to determine the type, why is there an isinstance?
An obvious difference is that the subclass is determined.
Type () is not considered as a type of parent class.
Isinstance () considers subclass as a parent class type.
A thousand words is worse than a single code.
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 should be noted that the type () results of the old and new classes are different. All old classes are <type 'instance'>.
Class A: passclass B: passclass C (object): passprint 'old style class', type (A () print 'old style class', type (B ()) print 'new style class', type (C () print type (A () = type (B () class A: passclass B: passclass C (object ): passprint 'old style class', type (A () print 'old style class', type (B () print 'new style class', type (C ()) print type (A () = type (B ()) output the old style class <type 'instance'> new style class <class '_ main __. c'> True
If this parameter does not exist, isinstance is better than type. Only which one is more suitable for your needs.
Summary
The above is all about the parsing of the instance for determining the difference between type and isinstance in python data type. I hope it will be helpful to you. Interested friends can continue to refer to this site: Arrangement and combination on the blackboard of Python programming. Are you willing to solve it, and talk about some Thoughts Caused by _ dict _ and dir () in Python, if you have any questions, please leave a message to discuss them.