如何在Python中打印变量的类型

226 阅读2分钟

要在Python打印 变量类型,可以使用**type()** 函数。type()是一个内置的Python函数,它返回变量的数据类型。要打印 Python中的变量,使用print()函数。

要在Python中获得一个变量的数据类型,使用type() 函数。type()方法返回作为参数传递的参数(对象)的类别类型。如果输入的是一个列表,它将返回输出为 <class 'list'>,对于字符串,它将是 <class 'string'>,等等。

对于 type(),你可以传递一个参数,而返回值将是该参数的类类型。

语法

type(object)

参数

如果单个对象被传递给 type() ,该函数将返回其类型。

例子

让我们来打印不同类型的变量:

str = "Welcome to Guru99"
run = 100
rr = 7.7
complex_num = 19j+21
player_list = ["VK", "RS", "JB", "RP"]
bat_name = ("A", "B", "C", "D")
duckworth = {"A": "a", "B": "b", "C": "c", "D": "d"}
lbw = {'Y', 'N', 'T', 'F'}

print("The type is : ", type(str))
print("The type is : ", type(run))
print("The type is : ", type(rr))
print("The type is : ", type(complex_num))
print("The type is : ", type(player_list))
print("The type is : ", type(bat_name))
print("The type is : ", type(duckworth))
print("The type is : ", type(lbw))

输出结果

The type is :  <class 'str'>
The type is :  <class 'int'>
The type is :  <class 'float'>
The type is :  <class 'complex'>
The type is :  <class 'list'>
The type is :  <class 'tuple'>
The type is :  <class 'dict'>
The type is :  <class 'set'>

你可以看到,我们打印了不同变量的不同数据类型。

Python isinstance

isinstance()是一个内置的Python方法,如果一个指定的对象属于指定的类型,则返回True。isinstance()方法接受两个参数:objectclasstype,如果定义的 对象属于定义的 类型,则返回 True

语法

isinstance(object, classtype)

参数

object。它是一个对象,你要将其实例与类的类型进行比较。如果类型匹配,它将返回True,否则返回False。

类的类型:它是一个类型或一个类或一个类型和类的元组。

例子

在这个例子中,我们将用float类型来比较浮动值,即19.21的值将与float类型进行比较。

fvalue = 19.21
dt = isinstance(fvalue, float)
print("It is a float value:", dt)

输出

It is a float value: True

返回True

使用 isinstance() 方法,你可以测试字符串浮点、int、列表、元组dict、set、类等等。

不要使用 __class__

在 Python 中,以下划线开头的名字在语义上不是公共 API 的一部分。因此,除非必要,用户应该避免使用它们。

不要做下面的事情:

class Excol(object):
    def dol(self):
        self.__class__

相反,做下面的事:

class Excol(object):
    def dol(self):
        type(self)

这意味着总是使用type() 函数来确定 Python 中变量的数据类型。

本教程就到此为止。