python中我们会遇到动态创建一个类的需求,这里给出一种动态创建类的一种实现方法:
第一种,生成实例时,不需要传入参数的创建一个动态类:
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
p = Person('Hijacker', 23)
dog_class = type('Dog', (object, ), {"role": "dog"})
print(dog_class)
d = dog_class()
print(d.role)
第二种,需要传入参数的创建动态类
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
p = Person('Hijacker', 23)
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("Hijacker", 23)
print(d.role, d.name, d.age)
输出:
<class '__main__.Dog'>
dog Hijacker 23
|