How to check data type in python

藏色散人
Release: 2019-10-25 11:47:53
Original
4062 people have browsed it

How to check data type in python

How to check the data type in python?

In python, you can check the data type through the type() function.

Python built-in functions Python built-in functions

Python type() function returns the type of the object if you only have the first parameter, and the three parameters return the new type object.

isinstance() 与 type() 区别:
type() 不会认为子类是一种父类类型,不考虑继承关系。
isinstance() 会认为子类是一种父类类型,考虑继承关系。
Copy after login

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

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

type(object)
type(name, bases, dict)
Copy after login

Parameters

name: The name of the class.

bases: Tuple of base classes.

dict: dictionary, namespace variable defined within the class.

Return value

One parameter returns the object type, and three parameters return the new type object.

Example

The following shows an example of using the type function:

# 一个参数实例
>>> type(1)
<type &#39;int&#39;>
>>> type(&#39;school&#39;)
<type &#39;str&#39;>
>>> type([2])
<type &#39;list&#39;>
>>> type({0:&#39;zero&#39;})
<type &#39;dict&#39;>
>>> x = 1
>>> type( x ) == int # 判断类型是否相等
True
# 三个参数
>>> class X(object):
... a = 1
...
>>> X = type(&#39;X&#39;, (object,), dict(a=1)) # 产生一个新的类型 X
>>> X
<class &#39;__main__.X&#39;>
Copy after login

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
Copy after login

Recommendation: "pythontutorial

The above is the detailed content of How to check data type in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!