saei
saei

Reputation: 109

Python: how to catch calls to derived class?

Say I have a base class base and a derived class derive.

I want to do two things: override one method in base. This is done by simply overriding it in derive.

However, I also want to do something to all the other methods on base. What I want to do is simply call the base function's method, then multiply the result by -1.

As you can see, I am now forced to write out all these methods in derive, call the super().method, then multiply by -1 and return.

Is there not a way to catch all these other functions in derive, then do it for them all simultaneously?

class Base:
    def override():
        pass # override this manually in derived
    def method1():
        pass # multiply by -1 in derive
    def method2():
        pass # multiply by -1 in derive
    def method3():
        pass # multiply by -1 in derive
    def method4():
        pass # multiply by -1 in derive

class Derived(Base)

    # now what do I do here that avoids writing out all the methods??

Upvotes: 0

Views: 33

Answers (1)

Thomas
Thomas

Reputation: 182000

You can do this with a small change to the Base class, adding a _multiplier() method that you override in Derived:

class Base:
    def _multiplier():
        return 1
    def method1():
        return some_value * self._multiplier()
    def method2():
        return some_value * self._multiplier()
    def method3():
        return some_value * self._multiplier()
    def method4():
        return some_value * self._multiplier()

class Derived(Base):
    def _multiplier():
        return -1

Upvotes: 1

Related Questions