How to replace a base class with a subclass -- even when base methods return new base class instances

Viewed 75

I have a subclass that inherits from pandas.DataFrame and adds some new methods specific to my implementation. Those methods act on and return a modified version of self (basically just repeating the DataFrame pattern of chainable methods that already exists, but with extended functionality):

class Subclass(pandas.DataFrame):

    def new_method(self):
        return Subclass(self.transform(...))

When I define my own methods, it's easy to return new Subclass instances. However, when I call methods from the base class that aren't overridden, the returned result is a new DataFrame, not a new Subclass. So I lose any new functionality from my instance as soon as I use base class methods.

Is there a way (without overriding every method in the pandas.DataFrame base class that I suspect may be used in Subclass) of forcing the base class methods to return Subclass instances? In other words, wherever the DataFrame constructor is used within a Subclass instance, silently replace it with a Subclass constructor?

1 Answers

Looking at the documentation, it appears there is a solution provided for this.

In your class, you need to override this property and return your own class.

@property
def _constructor(self):
    return Sublclass

To keep with this pattern, you should also replace any Subclass calls when returning objects with references to _constructor so that any subclasses of your own class can also return Subsubclass rather than Subclass.

Related