Python Wrap Class Method

前端 未结 4 1662
逝去的感伤
逝去的感伤 2021-02-07 18:05

I\'m trying to create an object with a run method that will be wrapped by a _wrap_run method. I\'d like to be able to call the method and it\'s wrapper by simply ty

4条回答
  •  灰色年华
    2021-02-07 18:45

    Easiest way: make run the wrapper, and a private method be the overrideable one.

    class A(object):
        def run(self):
            print "PRE"
            return_value = self._inner_run()
            print "POST"
            return return_value
    
        def _inner_run(self):
            print "Run A"
            return True
    
    class B(A):
        def _inner_run(self):
            print "Run B"
            return True
    

提交回复
热议问题