美文网首页
Python内置函数-type()

Python内置函数-type()

作者: 莫忘初心_倒霉熊 | 来源:发表于2020-02-17 17:31 被阅读0次

type() 函数:

  • 只有一个参数,则返回对象的类型, 语法type(object)
  • 三个参数时,接受一个类的描述作为参数然后返回一个类,语法type(name,bases,dict)

参数

name -- 类名
bases -- 由父类名称组成的元祖(针对继承的情况,可以为空)
dict -- 包含属性的字典(名称和值)

实例

以下展示了使用 type 函数的实例:

# 一个参数实例
>>> type(1)
<type 'int'>
>>> type('runoob')
<type 'str'>
>>> type([2])
<type 'list'>
>>> type({0:'zero'})
<type 'dict'>
>>> x = 1          
>>> type( x ) == int    # 判断类型是否相等
True
 
# 三个参数
# 创建一个如下的简单类
# class Test1:
#      num =100
#      num2 =200
>>> Test1 =  type("Test1",(),{"num":100,"num2":200})
>>> Test1
<class '__main__.Test1'>
>>> Test1().num
100

# 一个复杂的类
class A(object):
    num = 100

def print_b(self):
    print(self.num)

@staticmethod
def print_static():
    print("--static--")

@classmethod
def print_class(cls):
    print(cls.num)

B = type("B",(A,),{'print_b':print_b,'print_static':print_static,'print_class':print_class})
b = B()
b.print_b()                                            # 100
b.print_static()                                       # --static--
b.print_class()                                        # 100

一个参数时,isinstance() 与 type() 区别:
type() 不会认为子类是一种父类类型,不考虑继承关系。
isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。

以下展示了type() 与 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内置函数-type()

      本文链接:https://www.haomeiwen.com/subject/kxtifhtx.html