Python:以编程方式创建基于__init__值的子类

use*_*435 4 python dynamic inner-classes

我有一个基类,我想从中创建许多子类.子类的不同之处仅在于在实例化期间用于调用基类的参数.下面的示例显示了如何创建子类Apple.有没有办法以编程方式执行此操作,而无需编写子类的__init__方法?这似乎是元类的工作,但在这种情况下我无法修改基类.

apple = {'color': 'red', 'shape': 'sphere'}
pear = {'color': 'yellow', 'shape': 'cone'}
melon = {'color': 'green', 'shape': 'prolate'}

class Fruit(object):
    def __init__(self, color, shape):
        self.color = color
        self.shape = shape        

class Apple(Fruit):
    def __init__(self):
        Fruit.__init__(self, **apple)
Run Code Online (Sandbox Code Playgroud)

use*_*876 6

请参阅type()函数.

def make_fruit(name, kwargs):
    def my_init(self):
        Fruit.__init__(self, **kwargs)
    return type(name, (Fruit,), {'__init__': my_init})

Apple = make_fruit('Apple', apple)
Run Code Online (Sandbox Code Playgroud)