现在,我的项目具有以下结构:
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)
------------------
这基本上意味着我要:
main_fun
到AuxOps
,CoreOps
,DerOps
和con_fun
中的每个方法/函数和变量。AuxOps
,CoreOps
和DerOps
的每个实现中有不同的方法/功能,应该在彼此的类中继承。即AuxOps
应该继承CoreOps
和DerOps
中的每个方法,DerOps
应该继承CoreOps
和AuxOps
中的每个方法。AuxOps
中CoreOps
,DerOps
和con_fun
中的每一个(继承它们会自动继承main_fun
,因为它是它们的父代吗?) 。如何实现以上目标?
答案 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.
“规则”是:
object
继承,除了定义普通方法外,不执行任何操作。 您可以在多个层次上重复此模式:
class FooFun( FooPlugin, ConFun):
# gets all of ConFun's plug-in methods, its base class, and added FooPlugin's methods
下一层,允许插入的方法拦截和增强从下一层继承的方法,并在适当的地方调用super().name()
。
关键是要找出什么指的是简单的东西。如果在插件中,则无需担心超类。对super()
的任何调用均引用基类,或者进一步引用其继承树。