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

标签 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

最佳答案

我想到了两个选择。首先,使用 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-framework 在其 Viewset 中使用此模式。代码。

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

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 替代方案更加困惑。

关于Python相同的代码但不同的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46621516/

相关文章:

python - Redis - 如何 RPUSH/LPUSH 一个空列表

javascript - Google App Engine Python、Jquery 和 Javascript 用于级联选择

linux - 如何检查和删除python中两个不同目录中不相同的文件?

python-3.x - Python git 包获取标签并提交

python - 从元组中删除空格

python - 如何使用zscan以相反的顺序遍历Redis中的排序集?

python - 统一码编码错误 : 'latin-1' codec can't encode character '\u2013' in position 637: ordinal not in range(256)

python-2.7 - 没有名为 ez_setup 的模块

Python3逐行读取混合文本/二进制数据

python - 根据可能采用多个值的参数有效地定义变量