标签:集合 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‘})
例二:
老规矩,来个熟悉的:
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‘>
再换个:
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上。
标签:集合 elf object 名称 nbsp 依次 f11 python span
原文地址:http://www.cnblogs.com/zhaochangbo/p/7717234.html