How to print instances of a class using print()?

前端 未结 9 1604
南方客
南方客 2020-11-21 07:27

I am learning the ropes in Python. When I try to print an object of class Foobar using the print() function, I ge

9条回答
  •  执念已碎
    2020-11-21 07:51

    >>> class Test:
    ...     def __repr__(self):
    ...         return "Test()"
    ...     def __str__(self):
    ...         return "member of Test"
    ... 
    >>> t = Test()
    >>> t
    Test()
    >>> print(t)
    member of Test
    

    The __str__ method is what happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.

    If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

提交回复
热议问题