Yon*_*tan 7 python inheritance implementation decorator wrapper
我的python代码中有以下情况:
class Parent(object):
def run(self):
print "preparing for run"
self.runImpl()
print "run done"
class Child(Parent):
def runImpl(self):
print "child running"
Run Code Online (Sandbox Code Playgroud)
但是,我有几个这样的"装饰",前后"runImpl"后做不同的安装/拆卸步骤,我不喜欢来定义run(),runImpl(),runImplSingleProcess()等.
我正在寻找以下形式的解决方案:
class Parent(object):
@wrapping_child_call
def run(self, func_impl, *args, **kwargs)
print "preparing for run"
func_impl(*args, **kwargs)
print "run done"
class Child(Parent):
def run(self):
print "child running"
Run Code Online (Sandbox Code Playgroud)
通过这种方式,Child类几乎不需要知道这种情况.
多继承也可能存在问题.如果一个Child继承自Parent1和Parent2,老实说我不知道应该是什么样的正确行为.
有谁知道一个好的,自然的,完成这个的方式?还是我在这里强奸设计?
谢谢
Yonatan
反转你的设计。与其采用“is-a”关系的父子实现,为什么不直接使用组合来获得“has-a”关系呢?您可以定义实现您想要的方法的类,而您以前的父类将使用这些实现特定的类进行实例化。
class MyClass:
def __init__(self, impl)
self.impl = impl
def run(self,var):
print "prepare"
impl.runImpl(var)
print "I'm done"
class AnImplementation:
def runImpl(self,var):
Run Code Online (Sandbox Code Playgroud)