Elegant Python-difference between type judgment and isinstance

Source: Internet
Author: User
In the game project, we verify the parameter type passed by the client 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. For example,> type ('foo') = strtrue> type (2.3) in (INT, float) True () 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): passclass bar (FOO): passprint type (FOO () = fooprint type (Bar () = fooprint isinstance (Bar (), foo)
Output truefalsetrue. Note that the type () results of the old class and the new class 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 ())
Output the old style class <type 'instance'> New Style Class <class '_ main __. C '> if true does not exist, isinstance is better than type. Only which one is more suitable for your needs.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.