Python相同的代码但不同的继承

时间:2017-10-07 14:49:39

标签: python python-2.7 python-3.x

我有两个实现某些方法的类(Parent1和Parent2)。然后我有两个类(Child1和Child2),它们应该从它们相应的Parent继承并实现一些函数。问题是Child1和Child2具有完全相同的逻辑,所以我希望有人可以指出我的可重用性解决方案。我正在研究条件继承,但不确定,因为它不是我所来自的语言中的东西。

简单的例子只是为了得到一个想法:

# In file1
class Parent1():
    def main_method(self):
        # Parent 1 implementation
        self.arr = [1, 2, 3]

# In file2
class Parent2():
    def main_method(self):
        # Parent 2 implementation
        self.arr = [2, 4, 6]

# In file3
class Child1(Parent1):
    def main_method(self):
        Parent1.main_method(self)
        # Child logic for main_method
        print self.arr

# In file4
class Child2(Parent2):
    def main_method(self):
        Parent2.main_method(self)
        # Child logic for main_method
        print self.arr

2 个答案:

答案 0 :(得分:3)

有两种选择可以想到。首先,使用Mixin通过继承添加功能。我觉得这是更多的Pythonic解决方案。请注意,Mixin需要是第一个继承的类,因此它首先出现在MRO中(否则将找到Parent方法。)

class Parent():
    def main_method(self):
        self.arr = [1, 2, 3]

class MethodMixin():
    def main_method(self):
        super(MethodMixin, self).main_method()
        print(self.arr)

class Child(MethodMixin, Parent): pass

我之前看到过这种方法取得了巨大成功。例如,django-rest-frameworkViewset代码中使用此模式。

第二个选项是使用元类在创建Child类时动态添加方法。

class MethodMeta(type):
    def __new__(cls, name, parents, dct):
        new_cls = super(MethodMeta, cls).__new__(cls, name, parents, dct)

        def main_method(self):
            super(new_cls, self).main_method()
            print(self.arr)

        new_cls.main_method = main_method
        return new_cls

class Child(Parent, metaclass=MethodMeta): pass

上面的代码片段使用Python 3.X元类语法。如果要在Python 2.X中使用元类,则必须将其添加为名为__metaclass__的类变量。请注意,这种元类方法并没有很好地扩展;如果你想用一个元类添加10个方法,那么它将比Mixin替代方案更加混乱。

答案 1 :(得分:0)

对我来说,父母成为孩子,反之亦然,这似乎更合乎逻辑。让我们。你可以做点什么

class Parent():
    def main_method(self):
        //the child logic in your code
        return self.arr

class Child1(Parent):
    def main_method(self):
       //parent1 logic in your code
       self.arr = [1,2,3]
       Parent.main_method(self)
            print self.arr 

class Child2(Parent):
      def main_method(self):
          //parent2 logic in your code
          self.arr = [2,4,6]
          Parent.main_method(self)
          print self.arr 

我真的不知道这对你的实际代码是否有意义,但通常commin逻辑位于父类中,而子类则为代码添加逻辑。希望这无论如何都会有所帮助。