Using __str__ representation for printing objects in containers in Python

前端 未结 3 807
后悔当初
后悔当初 2021-01-04 18:06

I\'ve noticed that when an instance with an overloaded __str__ method is passed to the print function as an argument, it prints as intended. Howeve

3条回答
  •  迷失自我
    2021-01-04 18:39

    Because when you print the list, generally you're looking from the programmer's perspective, or debugging. If you meant to display the list, you'd process its items in a meaningful way, so repr is used.

    If you want your objects to be printed while in containers, define repr

    class MyObject:
        def __str__(self): return ""
    
        __repr__ = __str__
    

    Of course, repr should return a string that could be used as code to recreate your object, but you can do what you want.

提交回复
热议问题