0

How to white toString function, or better make Python stringify object? Here the simple class:

class Point(object):
    def __init__(self, x, y):
        self.X = float(x)
        self.Y = float(y)

Next code

print Point(1.1,22)

Gives

<__main__.Point object at 0x0000000002E7A588>

I expect to achieve something like outputs standard object (time.struct_time(tm_year=2013, tm_mon=7, tm_mday=10, tm_hour=2, tm_min=52, tm_sec=49, tm_wday=2, tm_yday=191, tm_isdst=-1),) or Point(x=1.1,y=22)

What is proper function name? Should I write it by myself?

kyb
  • 7,233
  • 5
  • 52
  • 105
  • See http://stackoverflow.com/questions/8144026/how-to-define-a-str-method-for-a-class – Wiktor Stribiżew Sep 01 '16 at 11:42
  • 4
    You need to implement `__str__` that displays your object how you want when you print it – Padraic Cunningham Sep 01 '16 at 11:42
  • What they said. You need to give your class a `__str__` and / or a [`__repr__`](https://docs.python.org/3/reference/datamodel.html#object.__repr__) method. Also see http://stackoverflow.com/questions/3691101/what-is-the-purpose-of-str-and-repr-in-python – PM 2Ring Sep 01 '16 at 11:44
  • Possible duplicate of http://stackoverflow.com/questions/4912852/how-do-i-change-the-string-representation-of-a-python-class – Naveen Dennis Sep 01 '16 at 11:47
  • Another useful page on this topic is: http://stackoverflow.com/questions/1535327/how-to-print-a-class-or-objects-of-class-using-print FWIW, for this case, I'd make `__repr__` return something like `"Point(x=1.1, y=22)"` and `__str__` return `"(1.1, 22)"` – PM 2Ring Sep 01 '16 at 11:58

0 Answers0