Force child class to call parent method when overriding it

后端 未结 7 1940
梦谈多话
梦谈多话 2020-12-15 16:05

I am curious whether there is a way in Python to force (from the Parent class) for a parent method to be called from a child class when it is being overridden.

Examp

7条回答
  •  半阙折子戏
    2020-12-15 17:00

    If the class hierarchy is under your control, you can use what the Gang of Four (Gamma, et al) Design Patterns book calls the Template Method Pattern:

    class MyBase:
       def MyMethod(self):
          # place any code that must always be called here...
          print "Base class pre-code"
    
          # call an internal method that contains the subclass-specific code
          self._DoMyMethod()
    
          # ...and then any additional code that should always be performed
          # here.
          print "base class post-code!"
    
       def _DoMyMethod(self):
          print "BASE!"
    
    
    class MyDerived(MyBase):
       def _DoMyMethod(self):
          print "DERIVED!"
    
    
    b = MyBase()
    d = MyDerived()
    
    b.MyMethod()
    d.MyMethod()
    

    outputs:

    Base class pre-code
    BASE!
    base class post-code!
    Base class pre-code
    DERIVED!
    base class post-code!
    

提交回复
热议问题