[英]Override method on parent class
假设我们有这两类:
class B(A):
def process(self):
for item in self.items:
self.process_item(item)
class C(B):
def process(self):
# Do some other stuff
super(C, self).process()
现在,我想使用C
,但是我需要使process
表现如下:
def process():
# Do some other stuff
for item in self.items:
try:
self.process_item(item)
except ItemError as err:
handle_error(err)
我自然的方法是将C
子类化为D
并覆盖process
。 我不想重复#Do some other stuff
部分。 因此,基本上我需要更改B.process
的行为。 有什么优雅的方法可以做我想要的吗? 我没有A
, B
或C
由于C正确使用了super
,因此您可以做一些聪明的事情来弄乱方法的解析顺序,并将您自己的类放在B和C之间:
class Intermediate(B):
def process(self):
for item in self.items:
try:
self.process_item(item)
except ItemError as err:
handle_error(err)
class D(C, Intermediate):
pass
现在,给定D的实例,来自C.process的超级调用将调用Intermediate.process而不是B的版本。
这确实需要定义两个类,即使其中一个是空的也是如此,因此对于它是否比使用猴子补丁更干净还存在意见。
更新
鉴于此答案的注释中已有澄清,将C
子类化并使用它绝对是可行的方法。
先前
您可以猴子补丁A
def process(self):
amazing_stuff()
A.process = process
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.