Python data types determine the difference between type and isinstance

Source: Internet
Author: User
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.

  • 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.