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

Time:02-28

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?

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.

CodePudding user response:

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")
  • Related