在python开发中,我们创建类的常用方法就是硬编码使用class 关键字的方式实现,在运行时类与类方法已经实现:
class Person(object):
__name = 'Mick'
def __init__(self,name,age):
self.name = name
self.age = age
在这里,我介绍另一种方法实现创建类-——python动态创建类(Dynamically creating classes ),顾名思义,就是在运行时实现类的创建。python动态创建类我们使用关键字type来实现,type()说明如下:
type(name of the class,
#第一个参数是定义类名
tuple of the parent class (for inheritance, can be empty),
#第二个参数是继承的父类集合,可以是一个也可以是多个,以元组的类型列出
dictionary containing attributes names and values)
#第三个参数是类的属性参数或类的方法说明,可以是一个也可以是多个,以字典(Key:Value)类型列出
例如:
student = type('Student',(object,),{"__name":"This is a test.",'__init__':__init__,'study