-1

Best to explain with an example. I've defined a new class for a "point" object:

class point:

    def __init__(self, px, py):
        self.x = px
        self.y = py
        self.type = point

    def __str__(self):
        return "point(" + str(self.x) + ", " + str(self.y) + ")"

Now when I print a point all works well.

In [118]: p = point(2,5)

In [119]: print(p)
point(2, 5)

But being lazy I want the __str__ method to be returned when I just type p. Currently what I get is:

In [120]: p
Out[120]: <__main__.point at 0x1e446fffeb8>

while what I want is

In [120]: p
Out[120]: point(2, 5)

Is there a way to cause the __str__ to print by default when calling this type of object?

Aguy
  • 7,851
  • 5
  • 31
  • 58

1 Answers1

2

I believe what you're looking for is the __repr__ method.

zarak
  • 2,933
  • 3
  • 23
  • 29