gpt4 book ai didi

python - 在 Python 中进行微小更改来覆盖方法的正确方法

转载 作者:行者123 更新时间:2023-11-28 22:18:45 24 4
gpt4 key购买 nike

假设我有课

class Base(object):
def my_method(self, input):
print input #suppose this is many lines
print "mymethod" #so is this

和一个子类,它有一个方法几乎做同样的事情,除了在方法的中间有一个额外的操作,例如

class Sub(Base):
def mymethod(self, input): #how do I properly define this?
print input
print "some other stuff" #additional operation in the middle
print "mymethod"

覆盖 mymethod 的正确方法是什么?

  • 我是否复制并粘贴了大部分 Base.mymethod()? (可能不是——这绝对违反了 DRY)。
  • 我是否将 Base.mymethod() 定义为具有仅在子类情况下返回 true 的附加操作的条件语句? (可能不是——这没有意义,因为基类应该是独立的,这似乎是灾难的根源)
  • 我能以某种方式使用 super() 吗? (好像不是——Sub的附加操作是在方法的中间,不是开头也不是结尾)

最佳答案

对于这样一个简单的例子,我很可能会复制这三个小行,即使创建重复。尽量避免 over-engineering .

my_method()其实比较复杂的情况下,你可以把你的函数分成三步,让子类重载他们想要的部分。

class Base(object):

def my_method(self, input):
self._preprocess(input)
self._process()
self._postprocess()

def _preprocess(self, input):
print(input)

def _process(self):
pass

def _postprocess(self):
print("mymethod")


class Sub(Base):

def _process(self):
print("some other stuff")

当然你应该使用更有意义的方法名。

关于python - 在 Python 中进行微小更改来覆盖方法的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50260717/

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