P进阶(_isinstance_main函数和type函数)

本文详细介绍了Python内置的isinstance()和type()函数,包括它们的定义、源码示例以及使用场景。isinstance()不仅检查对象是否为指定类的实例,还考虑了继承关系,而type()则只判断对象的精确类型,不考虑继承。通过示例展示了这两个函数在处理类与子类关系时的不同行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

isinstance_main

定义:

"""
    返回对象是类的实例还是其子类的实例。一个元组,如“isinstance(x, (A, B, ...))”,
    可以作为检查的目标。这等价于 ``isinstance(x, A) or isinstance(x, B) or ...`` 等。
"""

源码:

"""
    Return whether an object is an instance of a class or of a subclass thereof.
    
    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.
"""

举例:

a = "小A"
if isinstance(a, str):
    print("小A是字符串")

if isinstance(a, (str, int, list)):
    print("小A是字符串,属于元祖中的一个类型")

print(isinstance(a, str))  # True
print(isinstance(a, (str, int, list)))  # True

type

print(type(a))  # <class 'str'>

定义:

"""
    type(object) -> 对象的类型 type(name, bases, dict, kwds) -> 新类型(从类文档复制)

"""

源码:

type(object) -> the object's type
type(name, bases, dict, **kwds) -> a new type
# (copied from class doc)

两者区别:

# type() 不会认为子类是一种父类类型,不考虑继承关系。isinstance() 会认为子类是一种父类类型,考虑继承关系


class A:
    pass


class B(A):
    pass


print(isinstance(A(), A))  # True
print(type(A()) == A)  # True
print(isinstance(B(), A))  # True
print(type(B()) == A)  # False 不继承父类类型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值