Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make object able to return its properties when triggered by print function

In python if we print some object, it will show their properties when triggered by print function.
For example:

print(int(69)) # 69

Unlike my own defined class like this:

class Foo:
  def __init__(self,oke):
    self.oke = oke

print(Foo('yeah')) # <__main__.Foo object at 0x000001EB00CDEEB0>

Why It doesn’t return oke properties? Instead it show memory address of object?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I expect the output will be:

Foo(oke='yeah')

I know I can define method getter get_oke(), but I want see all properties in an object at once print.

>Solution :

Add a __repr__ method to your class.

From the docs

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value

class Foo:
    def __init__(self,oke):
        self.oke = oke

    def __repr__(self):
        return f'Foo(oke="{self.oke}")'


print(Foo('yeah'))  # Foo(oke="yeah")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading