python Class:面向对象高级编程 元类:type
type的用法:
1、普通的type用法:检查类型
classmy(object):defhello(self,name='world'):print('Hello,%s.'%name)h=my()print(type(my))print(type(h))
运行结果:
<type'type'><class'__main__.my'>
my是class, 所以它的类型是type,
h是class的实例,所以它的类型是class my。
2、动态创建Class
格式:
a.定义一个函数,
b.实体类名 = type(类名, (继承, ), dict(类的方法=函数))
deffn(self,name='world'):#先定义函数print('Hello,%s.'%name)hl=type('Hello',(object,),dict(hello=fn))#创建Helloclassh=hl()h.hello()
运行结果:
Hello,world.
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。