Python相同的代码但不同的inheriten

2024-04-24 22:33:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个类(Parent1和Parent2)实现了一些方法。然后我有两个类(Child1和Child2),它们应该从相应的父类继承并实现一些函数。问题是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

Tags: inselfchildmaindefmethodimplementationclass
2条回答

在我看来,父母变成孩子更合乎逻辑,反之亦然。你可以这样做

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逻辑放在父类中,而子类向代码添加逻辑。希望这能有所帮助

我想到了两个选择。首先,使用Mixin通过继承添加功能。我觉得这是一个更具Python性的解决方案。注意,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-framework在其^{}代码中使用此模式

第二种选择是使用元类在创建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

上面的代码段使用python3.X元类语法。如果要在Python2.X中使用元类,必须将其添加为名为__metaclass__的类变量。注意,这种元类方法的伸缩性不是很好;如果您想添加10个带有元类的方法,那么它将比Mixin方法要复杂得多

相关问题 更多 >