gpt4 book ai didi

python父类 'wrapping'子类方法

转载 作者:太空狗 更新时间:2023-10-29 21:53:46 25 4
gpt4 key购买 nike

我的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"

但是,我有几代这样的“装饰器”的案例,在“runImpl”之前和之后执行不同的设置/拆卸步骤,目前我被迫定义run()runImpl()runImplSingleProcess() 在我的类 ParentChildChildSingleProcess 中。

我正在寻找以下形式的解决方案:

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类几乎不需要知道这件事。

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

有谁知道一个好的、自然的方法来完成这个?还是我在这里强奸了设计?

谢谢
与那滩

最佳答案

不要在这里使用继承

反转你的设计。而不是父子实现是一种“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):

关于python父类 'wrapping'子类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2065112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com