In Python, use Isinstance () to determine the variable type

Source: Internet
Author: User
First, Isinstance ()

In Python, you can use the type () and isinstance () functions to determine the object type, while the isinstance () function is more convenient to use than type.
Copy the Code code as follows:


# Coding=utf-8

A = 10

def b ():
Pass

Print Isinstance (A, (INT,STR))
Print Isinstance (A, (FLOAT,STR))
Print isinstance (b, (Str,int))

Class C:
Pass

obj = C ()

Print isinstance (obj, (c,int))


Execution Result:
Copy the Code code as follows:


True
False
False
True

Ii. the difference between isinstance and type

The difference between isinstance and type is:
Copy the Code code as follows:


Class A:
Pass

Class B (A):
Pass

Isinstance (A (), a) # returns True
Type (A ()) = = a # returns True
Isinstance (B (), A) # returns True
Type (B ()) = = A # returns False


The difference is that the type of subclass is not available, so it is strongly recommended that you do not use type to determine object types.
  • Related Article

    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.