Python中的类,继承和方法/函数

时间:2019-03-28 10:45:49

标签: python python-2.7 class inheritance

现在,我的项目具有以下结构:

main.py
-------

class main_fun(object):
    def __init__(self, <parameters>):


ops.py
------

class ops_fun(main_fun):
    def __init__(self):
        super(ops_fun, self).__init__(<parameters>)

它实质上翻译为以下内容:

                              ------------------
                              main_fun (main.py)
                              ------------------
                                      |
                                      |
                               ----------------
                               ops_fun (ops.py)
                               ----------------

我想将以上内容拆分/重组为以下内容:

                              ------------------
                              main_fun (main.py)
                              ------------------
                            /         |          \
                           /          |           \
        ----------------     ----------------      ----------------
        AuxOps (aops.py) === CoreOps (cops.py) === DerOps (dops.py)
        ----------------     ----------------      ----------------
                           \          |           /
                            \         |          /
                              ------------------
                              con_fun (contf.py)
                              ------------------

这基本上意味着我要:

  1. 继承类main_funAuxOpsCoreOpsDerOpscon_fun中的每个方法/函数和变量。
  2. AuxOpsCoreOpsDerOps的每个实现中有不同的方法/功能,应该在彼此的类中继承。即AuxOps应该继承CoreOpsDerOps中的每个方法,DerOps应该继承CoreOpsAuxOps中的每个方法。
  3. 继承AuxOpsCoreOpsDerOpscon_fun中的每一个(继承它们会自动继承main_fun,因为它是它们的父代吗?) 。

如何实现以上目标?

2 个答案:

答案 0 :(得分:3)

Python允许多重继承,因此您可以直接

class Parent ...

class ChildA(Parent) ...
class ChildB(Parent)...

class Grandchild(ChildA, ChildB)...

子级继承其所有父级方法。这导致了Grandchild将通过两个父级继承Parent类的方法的问题。默认情况下,当要求调用该方法时,python首先会查看最左边的父类。

有关更多详细信息,请查找钻石问题 python的方法解析顺序

答案 1 :(得分:2)

一个自以为是的答案。我建议使用基类和插件组成。通用类的多重继承可能很难调试。

class AuxPlugin( object):
    def auxMethod1( self, ...)

    ...

class CorePlugin( object)
    def coreMethod1( self, ...)
    ...

class DerPlugin( object)
    def derMethod1( self, ...)
    ...

class AuxOps( AuxPlugin, Main_Fun):  # better, call Main_Fun Base_whatever
    pass
class CoreOps( CorePlugin, Main_Fun):  
    pass
class DerOps( DerPlugin, Main_Fun): 
    pass
class ConFun( AuxPlugin, CorePlugin, DerPlugin, Main_Fun ):
    pass
# and possible
# class CoreDerOps( CorePlugin, DerPlugin, Main_Fun):
#    pass
# etc. Mix'n'match.

“规则”是:

  1. 插件始终从object继承,除了定义普通方法外,不执行任何操作。
  2. 在继承基类的类中,所有插件均位于单个基类的左侧
  3. 插件应具有与其他兼容插件不重叠的独特方法集(但如果这样做,则最左边的插件将获胜)
  4. 如果您违反这些规则,以后您会忘记后悔,否则会后悔,否则其他可怜的草皮将诅咒您并损害您的业力​​。

您可以在多个层次上重复此模式:

class FooFun( FooPlugin, ConFun):  
   # gets all of ConFun's plug-in methods, its base class, and added FooPlugin's methods

下一层,允许插入的方法拦截和增强从下一层继承的方法,并在适当的地方调用super().name()

关键是要找出什么指的是简单的东西。如果在插件中,则无需担心超类。对super()的任何调用均引用基类,或者进一步引用其继承树。