type动态创建类

在一些特定场合,需要动态创建类,比如创建表单,就会用到type动态创建类,举个例子:

 1 class Person(object):
 2 
 3     def __init__(self,name,age):
 4         self.name = name
 5         self.age = age
 6 
 7 
 8 p = Person("aiden",22)
 9 print(type(p))
10 print(type(Person))
11 
12 
13 
14 def __init__(self,name,age):
15     self.name = name
16     self.age = age
17 
18 dog_class = type("Dog",(object,),{"role":"dog","__init__":__init__})   #动态添加属性与方法
19 print(dog_class)
20 
21 d = dog_class('mjj',22)
22 print(d.role,d.name,d.age)

 

posted @ 2019-08-29 12:36  Aiden_Shao  阅读(157)  评论(0编辑  收藏  举报