Home >Backend Development >Python Tutorial >How to determine data type in python

How to determine data type in python

藏色散人
藏色散人Original
2019-10-19 11:29:267370browse

How to determine data type in python

How does python determine the data type?

In python, you can use the isinstance() function to determine the data type. The isinstance() function is used to determine whether an object is a known type, similar to type().

Recommended: "Python Tutorial"

The difference between isinstance() and type():

type() will not The subclass is considered to be a parent class type and the inheritance relationship is not considered.

isinstance() will consider the subclass to be a parent class type and consider the inheritance relationship.

If you want to determine whether two types are the same, it is recommended to use isinstance().

Syntax

The following is the syntax of the isinstance() method:

isinstance(object, classinfo)

Parameters

object -- Instance object.

classinfo -- Can be a direct or indirect class name, a basic type, or a tuple consisting of them.

Return value

If the type of the object is the same as the type of parameter two (classinfo), it returns True, otherwise it returns False. .

Example

The following shows an example of using the isinstance function:

>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
True

The difference between type() and isinstance():

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 above is the detailed content of How to determine data type in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn