In Python, use isinstance () to determine the variable type, pythonisinstance

Source: Internet
Author: User

In Python, use isinstance () to determine the variable type, pythonisinstance

I. isinstance ()

In Python, you can use the type () and isinstance () functions to determine the object type. The isinstance () function is more convenient to use than the type function.
Copy codeThe Code is 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 codeThe Code is as follows:
True
False
False
True

Ii. Differences between isinstance and type

The difference between isinstance and type is:
Copy codeThe Code is as follows:
Class:
Pass

Class B ():
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 subclass and other types will not work. Therefore, we strongly recommend that you do not use type to determine the object type.


How does python determine that a variable is a list?

This does not seem to be the case with isinstance. I usually use type

X = int (5)
If type (x) = int: print "x is interger ."
Else: print "false ."

Isinstance can be used to determine whether a variable belongs to a class. It should be correct in python.

If type (x) = list: pass

If type (x) = dict: pass

What are the functions and usage of isinstance () in python?

Isinstance is rarely used. It is used only when some object-oriented production models are used. It is usually used to determine the inheritance relationship of a class.

>>> Class:
... V1 = 1
...
>>> Class B:
... V2 = 2
...
>>> Class c ():
... V1 = 3
...
>>> X = c ()
>>> Isinstance (x,)
True
>>> Isinstance (x, c)
True
>>> Isinstance (x, B)
False
>>>
 

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.