type动态创建类

时间:2024-12-27 18:07:50

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

 class Person(object):

     def __init__(self,name,age):
self.name = name
self.age = age p = Person("aiden",22)
print(type(p))
print(type(Person)) def __init__(self,name,age):
self.name = name
self.age = age dog_class = type("Dog",(object,),{"role":"dog","__init__":__init__}) #动态添加属性与方法
print(dog_class) d = dog_class('mjj',22)
print(d.role,d.name,d.age)