具有可变父类对象的Python类

具有可变父类对象的Python类,python,class,inheritance,Python,Class,Inheritance,很抱歉,我没有用一般的例子来解释我的问题。我知道这与机器学习无关,但我试着写一个通用的例子,它让人更加困惑,所以我决定继续:我有两个父类,比方说 class MLP(object): def __init__(self, mlp_architecture): ... def forward(self): ... class CNN(object): def __init__(self, cnn_architecture):

很抱歉,我没有用一般的例子来解释我的问题。我知道这与机器学习无关,但我试着写一个通用的例子,它让人更加困惑,所以我决定继续:我有两个父类,比方说

class MLP(object):
    def __init__(self, mlp_architecture):
        ...
    def forward(self):
        ...
class CNN(object):
    def __init__(self, cnn_architecture):
        ...
    def forward(self):
        ...
class Classifier(Model):
    def __init__(self, num_epochs, 
                       learning_rate,
                       ...
                       model_architecture):
        super(Classifier, self).__init__(model_architecture)
    def train(self):
        ...
    def predict(self, x):
        ...
比如说,我有一个儿童班

class MLP(object):
    def __init__(self, mlp_architecture):
        ...
    def forward(self):
        ...
class CNN(object):
    def __init__(self, cnn_architecture):
        ...
    def forward(self):
        ...
class Classifier(Model):
    def __init__(self, num_epochs, 
                       learning_rate,
                       ...
                       model_architecture):
        super(Classifier, self).__init__(model_architecture)
    def train(self):
        ...
    def predict(self, x):
        ...
现在,
Classifier
的方法既适用于
MLP
又适用于
CNN
,它们需要一种
forward
方法。我希望
Classifier
能够从
MLP
CNN
继承
forward
,而不必像这样定义两个子类

class ClassifierMLP(MLP):
    ...
class ClassifierCNN(CNN):
    ...
相反,我想这样做(我知道我写的是错的,但我希望你能理解)


正确的方法是什么?另外,如果您想知道“为什么麻烦”、
Classifier
MLP
CNN
实际上有更多的方法,我也有更多的父类,我希望从中继承分类器,所以我想如果我能够做到这一点,我的程序会简单得多。提前谢谢

所以你想要的是一个
分类器
,它可以有来自
MLP
CNN
的方法。Python是一种非常灵活的语言,你肯定会找到一种使用继承来解决这个问题的方法,但也许“保持简单”的方法会更好?尝试使用组合而不是继承。也许
MLP
/
CNN
应该从
分类器继承,而不是相反。或者您可以将一个普通成员
模型
添加到
分类器
,并在其构造函数中传递
MLP
CNN
。@dhke这是我第一次听说mixin,所以可能我错了,但据我所知,它继承了多个类的方法。在我的例子中,
MLP
CNN
有几乎相同的方法(例如
forward()
forward()
MLP
CNN
中具有相同的输出类型,但方法定义不同。因此,如果我从这两个类继承,我需要一个字符串变量,比如
model\u name
,来指定从哪个类继承(使用
if-else
)。非常感谢您的评论。我想我会做一些简单的事情。