zoukankan      html  css  js  c++  java
  • Python 变量类型 —— type() 函数和 isinstance() 函数

    type() 函数的语法:

    class type(name, bases, dict)

    name -- 类的名称,bases -- 基类的元组,dict -- 字典,类内定义的命名空间变量
    如果只有第一个参数则返回对象的类型;如果有三个参数返回新的类型对象。

    示例:
    # 一个参数实例
    >>> type(1)
    <type 'int'>
    >>> type('runoob')
    <type 'str'>
    >>> type([2])
    <type 'list'>
    >>> type({0:'zero'})
    <type 'dict'>
    >>> x = 1          
    >>> type( x ) == int    # 判断类型是否相等
    True
     
    
    # 三个参数
    >>> class X(object):
    ...     a = 1
    ...
    >>> X = type('X', (object,), dict(a=1))  # 产生一个新的类型 X
    >>> X
    <class '__main__.X'>

    isinstance() 与 type() 区别:

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

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

    • 如果要判断两个类型是否相同推荐使用 isinstance()。
    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
  • 相关阅读:
    『Python基础』第3节:变量和基础数据类型
    Python全栈之路(目录)
    前端
    Python十讲
    Ashampoo Driver Updater
    druid 连接池的配置
    webService 入门级
    pom
    pom----Maven内置属性及使用
    webservice 总结
  • 原文地址:https://www.cnblogs.com/shilxfly/p/7641246.html
Copyright © 2011-2022 走看看