1

I am just getting started with OOP, so I apologise in advance if my question is as obvious as 2+2. :)

Basically I created a class that adds attributes and methods to a panda data frame. That's because I am sometimes looking to do complex but repetitive tasks like merging with a bunch of other tables, dropping duplicates, etc. So it's pleasant to be able to do that in just one go with a predefined method. For example, I can create an object like this:

mysupertable = MySupperTable(original_dataframe)

And then do:

mysupertable.complex_operation()

Where original_dataframe is the original panda data frame (or object) that is defined as an attribute to the class. Now, this is all good and well, but if I want to print (or just access) that original data frame I have to do something like

print(mysupertable.original_dataframe)

Is there a way to have that happening "by default" so if I just do:

print(mysupertable)

it will print the original data frame, rather than the memory location?

I know there are the str and rep methods that can be implemented in a class which return default string representations for an object. I was just wondering if there was a similar magic method (or else) to just default showing a particular attribute. I tried looking this up but I think I am somehow not finding the right words to describe what I want to do, because I can't seem to be able to find an answer.

Thank you! Cheers

Berti1989
  • 185
  • 1
  • 14
  • If you want to be able to access any attribute/method of the original df, maybe you want to [subclass Dataframe](https://stackoverflow.com/questions/22155951/how-can-i-subclass-a-pandas-dataframe)? – Thierry Lathuille Nov 10 '22 at 16:19

2 Answers2

5

In your MySupperTable class, do:

class MySupperTable:

    # ... other stuff in the class

    def __str__(self) -> str:
        return str(self.original_dataframe)

That will make it so that when a MySupperTable is converted to a str, it will convert its original_dataframe to a str and return that.

Samwise
  • 68,105
  • 3
  • 30
  • 44
1

When you pass an object to print() it will print the object's string representation, which under the hood is retrieved by calling the object.__str__(). You can give a custom definition to this method the way that you would define any other method.

Dakeyras
  • 1,829
  • 5
  • 26
  • 33