【Python】Python 如何判断变量类型?——python isinstance()详解

isinstance()的作用

isinstance() 函数来判断一个对象是否是一个已知的类型。

isinstance() 解释

isinstance(object, classinfo):

Return True if the object argument is an instance of the classinfo
argument, or of a (direct, indirect, or virtual) subclass thereof. If
object is not an object of the given type, the function always returns
False. If classinfo is a tuple of type objects (or recursively, other
such tuples) or a Union Type of multiple types, return True if object
is an instance of any of the types. If classinfo is not a type or
tuple of types and such tuples, a TypeError exception is raised.

如果 object 参数是 classinfo 参数的实例,或其(直接、间接或 virtual )子类的实例,则返回 True。 如果 object 不是给定类型的对象,则总是返回 False。如果 classinfo 是类型对象的元组(或由该类元组递归生成)或多个类型的 Union Type,那么当 object 是其中任一类型的实例时就会返回 True。如果 classinfo 不是某个类型或类型元组,将会触发 TypeError 异常。

和type()的区别

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

isinstance() 实例参考

>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
True# isinstance()与type()的区别
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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

别出BUG求求了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值