python父类'包装'子类方法 [英] python parent class 'wrapping' child-class methods

查看:141
本文介绍了python父类'包装'子类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的python代码中有以下情况:

I have the following situation in my python code:

class Parent(object):
    def run(self):
        print "preparing for run"
        self.runImpl()
        print "run done"

class Child(Parent):
    def runImpl(self):
        print "child running"

但是,我有几个这样的'装饰者',在'runImpl'之前和之后做不同的设置/拆卸步骤,我不喜欢定义 run() runImpl( ) runImplSingleProcess()等。

However, I have several such 'decorators', doing different setup/teardown steps before and after 'runImpl', and I don't like having to define run(), runImpl(), runImplSingleProcess() etc.

我正在寻找一个解决方案以下表格:

I am looking for a solution of the following form:

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"

通过这种方式,Child类几乎不需要知道这种情况。

In this way, there is almost no need for Child class to be aware of this going on.

多重继承可能存在问题。如果 Child 继承自 Parent1 Parent2 ,我老实说不知道应该是什么样的正确行为。

There may also be an issue with multiple inheritance. If a Child inherits from Parent1 and Parent2, I honestly don't know what should be the correct behavior.

有没有人知道一种好的,自然的方式来实现这个目标?或者我在这里强调设计?

Does anyone know a good, natural, way of accomplishing this? or am I raping the design here?

谢谢

Yonatan

Thanks
Yonatan

推荐答案

不要在这里使用继承



反转你的设计。而不是一个is-a关系的父子实现,为什么不只是有一个组合,所以你得到一个有一个的关系?您可以定义实现您想要的方法的类,而您的上一个父类将使用这些特定于实现的类进行实例化。

Don't use inheritance here

Invert your design. Instead of a parent-child implementation which is a "is-a" relationship why not just have a composition so you get a "has-a" relationship? You could define classes which implement the methods you'd like while your previous parent class would be instantiated with those implementation specific classes.

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):

这篇关于python父类'包装'子类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆