type() 和 isinstance() 在 Python 与例子

⚡ 智能摘要

Python `type()` 和 `isinstance()` 是用于检查对象所属类的内置函数。`type()` 返回确切的类型,而 `isinstance()` 则测试对象是否属于某个类或类元组。以下示例展示了这两个函数的用法。

  • 🔍 类型(): 返回对象的确切类别,例如 str、int 或 list。
  • ✅ isinstance(): 检查对象是否为给定类的实例,返回 True 或 False。
  • 🧩 三参数 type(): type(name, bases, dict) 动态创建一个全新的类对象。
  • 🌳 子类: isinstance() 对子类返回 True;type() 只检查确切的类。
  • 🎯 用例: 按对象类型验证输入类型、调试变量和分支逻辑。
  • 🤖 人工智能帮助: 像 Copilot 这样的 AI 工具可以根据需要生成 type() 和 isinstance() 检查。

type() 和 isinstance() 在 Python

type() 是什么 Python?

Python has a built-in function called type() that helps you find the class type of the variable given as input. For example, if the input is a string, you will get the output as <class 'str'>, for the list, it will be <class 'list'>, etc.

使用 type() 命令,您可以传递单个参数,返回值将是给定参数的类类型,例如:type(object)。

也可以将三个参数传递给 type(),即 type(name、bases、dict),在这种情况下,它将返回一个新的类型对象。

type() 的语法

type() 有两种使用方式,如下所示:

 type(object)
type(namr, bases, dict)

参数:类型(对象)

  • object:这是必需的参数。如果这是传递给 type() 的唯一参数,那么它将返回参数的类型。

参数:类型(名称,基础,字典)

  • name:类的名称。
  • bases:(可选)。这是一个可选参数,它是基类
  • dict:(可选)。这是一个可选参数,它是一个包含类定义的命名空间。

回报值

如果对象是传递给 type() 的唯一参数,那么它将返回对象的类型。

如果传递给类型的参数是类型(object,bases,dict),在这种情况下,它将返回一种新类型的对象。

type() 的示例

在此示例中,我们有一个字符串值、数字、浮点值、复数、列表、元组、字典和集合。我们将使用具有类型的变量来查看每个变量的输出。

str_list = "Welcome to Guru99"
age = 50
pi = 3.14
c_num = 3j+10
my_list = ["A", "B", "C", "D"]
my_tuple = ("A", "B", "C", "D")
my_dict = {"A":"a", "B":"b", "C":"c", "D":"d"}
my_set = {'A', 'B', 'C', 'D'}

print("The type is : ",type(str_list))
print("The type is : ",type(age))
print("The type is : ",type(pi))
print("The type is : ",type(c_num))
print("The type is : ",type(my_list))
print("The type is : ",type(my_tuple))
print("The type is : ",type(my_dict))
print("The type is : ",type(my_set))

输出:

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'>

示例:对类对象使用 type()。

当您使用 type() 检查从类创建的对象时,它会返回类类型以及类的名称。在此示例中,我们将创建一个类并检查从类测试创建的对象类型。

class test:
    s = 'testing'

t = test()
print(type(t))

输出:

<class '__main__.test'>

示例:在 type() 中使用 name、bases 和 dict

也可以使用以下语法来调用类型:type(name, bases, dict)。

传递给type()的三个参数即name、bases和dict是组成类定义的组件。name表示类名,bases是基类,dict是基类属性的字典。

在这个例子中,我们将使用 type() 中的所有三个参数,即 name、bases 和 dict。

计费示例:

class MyClass:
  x = 'Hello World'
  y = 50

t1 = type('NewClass', (MyClass,), dict(x='Hello World', y=50))
print(type(t1))
print(vars(t1))

输出:

<class 'type'>
{'x': 'Hello World', 'y': 50, '__module__': '__main__', '__doc__': None}

当您将所有三个参数传递给 type() 时,它可以帮助您使用基类属性初始化新类。

isinstance() 是什么 Python?

Python isinstance 是 python 内置函数. Python isinstance() 接受两个参数,如果第一个参数是第二个参数给出的 classinfo 的实例,则返回 true。

语法 isinstance()

isinstance(object, classtype)

参数

  • object:要将其实例与 classtype 进行比较的对象。如果类型匹配则返回 true,否则返回 false。
  • 类类型:一种类型、一个类、或者一个类型和/或类的元组。

返回值

如果对象是 classtype 的实例,它将返回 true,否则返回 false。

isinstance() 的示例

在本节中,我们将研究各种示例来学习 isinstance()

例如:isinstance() 整数检查

下面的代码将整数值 51 与类型 int 进行比较。如果 51 的类型与 int 匹配,则返回 true,否则返回 false。

age = isinstance(51,int)
print("age is an integer:", age)

输出:

age is an integer: True

例如:isinstance() 浮点检查

在这个例子中,我们将把浮点值与浮点类型进行比较,即将 3.14 值与浮点类型进行比较。

pi = isinstance(3.14,float)
print("pi is a float:", pi)

输出:

pi is a float: True

示例:isinstance() 字符串检查

message = isinstance("Hello World",str)
print("message is a string:", message)

输出:

message is a string: True

例如:isinstance() 元组检查

代码检查元组 (1,2,3,4,5) 的类型是否为 tuple。如果给定的输入是 tuple 类型,则返回 true,否则返回 false。

my_tuple = isinstance((1,2,3,4,5),tuple)
print("my_tuple is a tuple:", my_tuple)

输出:

my_tuple is a tuple: True

例如:isinstance() 设置检查

代码检查集合 ({1,2,3,4,5},类型为 set。如果给定的输入是 set 类型,则返回 true,如果不是,则返回 false。

my_set = isinstance({1,2,3,4,5},set)
print("my_set is a set:", my_set)

输出:

my_set is a set: True

示例:isinstance() 列表检查

代码检查列表 [1,2,3,4,5],类型为列表。如果给定的输入是列表类型,则返回 true,否则返回 false。

my_list = isinstance([1,2,3,4,5],list)
print("my_list is a list:", my_list)

输出:

my_list is a list: True

示例:isinstance() 字典检查

The code checks for a dict({"A":"a", "B":"b", "C":"c", "D":"d"},with type dict. It will return true if the input given is of type dict and false if not.

my_dict = isinstance({"A":"a", "B":"b", "C":"c", "D":"d"},dict)
print("my_dict is a dict:", my_dict)

输出:

my_dict is a dict: True

示例:对类进行 isinstance() 测试

代码显示了使用 isinstance() 进行类的类型检查。将类的对象与 isinstance() 中的类名进行比较。如果对象属于该类,则返回 true,否则返回 false。

class MyClass:
    _message = "Hello World"

_class = MyClass()

print("_class is a instance of MyClass() : ", isinstance(_class,MyClass))

输出:

_class is a instance of MyClass() True

type() 和 isinstance() 之间的区别 Python

类型() 实例()
Python 有一个名为 type() 的内置函数,可以帮助您找到作为输入的变量的类类型。 Python 有一个内置函数 isinstance(),用于将值与给定的类型进行比较。如果给定的值和类型匹配,则返回 true,否则返回 false。
返回值是一个类型对象 返回值是布尔值,即真或假。
class A:
my_listA = [1,2,3]

class B(A):
my_listB = [1,2,3]

print(type(A()) == A)
print(type(B()) == A)

输出:

True
False

如果类型正确,子类检查将返回 false。

class A:
my_listA = [1,2,3]

class B(A):
my_listB = [1,2,3]

print(isinstance(A(), A))
print(isinstance(B(), A))

输出:

True
True

isinstance() 使用子类检查时会给出真实值。

常见问题

type() 是一个内置函数,用于返回对象的类。如果传递一个参数,则返回对象类型;如果传递三个参数(名称、基类、字典),则创建一个新类。

isinstance(object, classtype) 检查一个对象是否是某个类或类元组的实例。如果类型匹配,则返回 True,否则返回 False。

`type()` 返回对象的确切类名,并且忽略继承关系;而 `isinstance()` 对子类也返回 True。使用 `isinstance()` 可以进行灵活的类型检查,并考虑类层次结构。

是的。调用带有三个参数的 type(name, bases, dict) 函数会动态地返回一个新的类对象。name 是类名,bases 是父类的元组,dict 包含属性。

是的。当一个对象是某个类或其任何子类的实例时,`isinstance()` 函数返回 `True`。这使得它在检查继承类型时比 `type()` 函数更安全。

GitHub Copilot 等 AI 助手会在你编写代码时自动补全 type() 和 isinstance() 函数,生成验证规则,并针对给定对象建议正确的处理方法。 Python.

是的。人工智能工具可以自动插入 isinstance() 保护语句,检测未经检查的输入,并将脆弱的 type() 比较重构为更安全的 isinstance() 检查,从而保护您的整个代码库。

`type()` 方法返回与值对应的类对象:列表对应 `list`,字典对应 `dict`。打印结果会显示类似 `class list` 或 `class dict` 的形式。

总结一下这篇文章: