python中type与isinstance异同

python中type与isinstance异同

2018年12月26日 15:55:48 bitcarmanlee 阅读数:12 标签: typeisinstance旧式类新式类更多

个人分类: python

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bitcarmanlee/article/details/85263614

在python中,经常会使用到type与isinstance两个内置的函数来判断变量属于什么类型。那么这两个函数有什么区别呢?下面来简单分析一下。

1.type

type函数的源码如下:

    def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
        """
        type(object) -> the object's type
        type(name, bases, dict) -> a new type
        # (copied from class doc)
        """
        pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

此部分代码位于__builtin__.py中。从这段代码可以看出,type函数的用法很简单,就是type(object),返回的是传入的object的类型。

2.isinstance

isinstance函数的源码:

def isinstance(p_object, class_or_type_or_tuple): # real signature unknown; restored from __doc__
    """
    isinstance(object, class-or-type-or-tuple) -> bool
    
    Return whether an object is an instance of a class or of a subclass thereof.
    With a type as second argument, return whether that is the object's type.
    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
    isinstance(x, A) or isinstance(x, B) or ... (etc.).
    """
    return False
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

isinstance的用法为:

isinstance(object,type-or-tuple-or-class) -> bool
传入的第一个参数为对象,第二个参数为类型名(int,str,float等)或者类型名的一个列表(如(str, str, int)为一个列表),返回值为一个布尔变量。

3.两个函数的异同

相同点
都可以判断变量是否属于某个内建类型。

不同点
1.type只接受一个参数,不仅可以判断变量是否属于某个类型,还可以直接返回参数类型。而isinstance只能判断是否属于某个已知的类型,不能直接得到变量所属的类型。

2.isinstance可以判断子类实例对象是属于父类的;而type会判断子类实例对象和父类类型不一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值