在一些特定场合,需要动态创建类,比如创建表单,就会用到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)
原文地址:https://www.cnblogs.com/intruder/p/11429061.html
时间: 2024-11-05 19:01:57