通过Python

时间:2018-05-09 19:26:14

标签: python oop override subclass method-overriding

说我有一个班级

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

和一个子类,它有一个几乎完全相同的方法,除了方法的 middle 中的额外操作,例如

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的附加操作是在方法的中间,而不是开头或结尾)

2 个答案:

答案 0 :(得分:2)

这取决于东西属于哪里。通常,如果您最终希望在base方法的操作之间插入东西,则意味着该方法实际上应该分成几个方法。

例如:

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

可能会成为:

class Base(object):
    def my_method(self, input):
        self.do_first_thing(input)
        self.do_second_thing("mymethod")

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

    def do_second_thing(self, data):
        print(data)

这使得子类可以重新定义整个过程,而无需重新实现每个步骤。这个概念类似于template method,但是向后。

(通常,模板方法模式的目的是让子类重新定义步骤,这里我们使用相同的结构让子类重新定义模板本身。)

答案 1 :(得分:2)

对于这样一个简单的例子,即使创造了重复,我也很可能会复制这三条小行。尽量避免使用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")

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