Home > Net >  Python: can an object have an object as a "default" representation?
Python: can an object have an object as a "default" representation?

Time:11-11

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related