码迷,mamicode.com
首页 > 其他好文 > 详细

type( ) 创建类

时间:2017-10-23 18:03:35      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:集合   elf   object   名称   nbsp   依次   f11   python   span   

对象是由类创建的,类是由type创建的。

 

熟悉的方式:

class A(object):
    pass

print(type(A))   #<class ‘type‘>

 

type方式:

A = type(A,(object,),{})

print(type(A))  #<class ‘type‘>

 

参数格式:

type(class_name,bases,dic)

要动态创建一个class对象,type()函数依次传入3个参数:

1、class的名称,字符串形式;
2、继承的父类集合,注意Python支持多重继承,如果只有一个父类,注意tuple的单元素写法;
3、{k:v} 或者 dict(k=v)

 

例一:

技术分享
class Foo(object):
    class Meta:
        model = qwer


由type创建:
_meta = type(Meta,(object,),{model:qwer})
Foo = type(Foo,(object,),{Meta:_meta})
View Code

 

例二:

老规矩,来个熟悉的:

技术分享
class Hello(object):

    def hw(self,name=World):
        print(Hello,%s%name)
        

h = Hello()
h.hw()

print(type(Hello))
print(type(h))


#输出结果:
# Hello,World
# <class ‘type‘>
# <class ‘__main__.Hello‘>
View Code

 

再换个:

技术分享
def func(self,name=World):
    print(Hello,%s%name)

Hello = type(Hello,(object,),{hw:func})

h = Hello()
h.hw()


print(type(Hello))
print(type(h))


#数据结果:
    # Hello,World
    # <class ‘type‘>
    # <class ‘__main__.Hello‘>
    
    
#注释:class的方法名称与函数绑定,这里我们把函数func绑定到方法名hw上。
View Code

 

type( ) 创建类

标签:集合   elf   object   名称   nbsp   依次   f11   python   span   

原文地址:http://www.cnblogs.com/zhaochangbo/p/7717234.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!