Timmmm
Timmmm

Reputation: 96556

Override a method without base class seeing it

This is a terrible idea, but I am refactoring some poorly designed code and this will make it easier.

In Python I would like to override a method, but have calls from the base class methods still use their own version. Something like this:

class Base:
  def foo(self):
    self.bar();

  def bar(self):
    return "base"

class Derived:
  def bar(self):
    return "derived"

d = Derived()
assert d.foo() == "base"
assert d.bar() == "derived"

Is something like that possible? Base is a built-in class so I cannot modify it.

Upvotes: 0

Views: 40

Answers (1)

Woody1193
Woody1193

Reputation: 7970

You're pretty close but the problem you'll have is that your code, as written, will produce the following:

>>> d = Derived()
>>> d.foo()
    "derived"
>>> d.bar()
    "derived"

There are two ways you can fix this. First, you can modify Base.foo so that it references Base explicitly:

class Base:

    def foo(self):
        return Base.bar(self)

    def bar(self):
        return "base"

However, my understanding is that you cannot modify Base. Therefore, your next best option would be to create a wrapper for Base and inherit from that:

class BaseWrapper:

    def __init__(self):
        self.inner = Base()

    def foo(self):
        self.inner.foo()

class Derived(BaseWrapper):

    def bar(self):
        return "derived"

This will produce the desired results with minimal maintenance effort on your part.

Upvotes: 1

Related Questions