当前位置: 移动技术网 > IT编程>脚本编程>Python > type()

type()

2019年06月07日  | 移动技术网IT编程  | 我要评论

besame mucho 王晰,红色海龟,kiss脳sis

type()函数既可以返回一个对象的类型,又可以创建出新的类型
通过type()函数创建的类和直接写class是完全一样的,因为python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class
正常情况下,我们都用class xxx...来定义类,但type()函数也允许动态创建出类来

 

  查看数据类型

  type()函数可以查看一个类型或变量的类型

     class hello(object):
          def hello(self, name='world'):
              print('hello, %s.' % name)
        
        
      from hello import hello
      h = hello()
      h.hello()    #输出:hello, world.
      print(type(hello))    #输出:<class 'type'>,hello是一个class,它的类型就是type
      print(type(h))    #输出:<class 'hello.hello'>,h是一个实例,它的类型就是class hello

  

  动态创建类

  type()函数既可以返回一个对象的类型,又可以创建出新的类型
  比如,可以通过type()函数创建出类,而无需通过class 类名(object)...的定义

  通过type()函数创建类,需依次传入3个参数:
    1) class的名称;
    2) 继承的父类集合,注意python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
    3) class的方法名称与函数绑定

        def fn(self, name='world'): # 先定义函数
            print('hello, %s.' % name)
            
        hello = type('hello', (object,), dict(hello=fn)) # 创建hello class,创建hello类,父类是object,类方法绑定的是fn
        h = hello()
        h.hello()    #输出:hello, world
        print(type(hello))    #输出:<class 'type'>
        print(type(h))    #输出:<class '__main__.hello'>

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网