Using __str__ representation for printing objects in containers in Python

前端 未结 3 806
后悔当初
后悔当初 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:50

    The problem with the container using the objects' __str__ would be the total ambiguity -- what would it mean, say, if print L showed [1, 2]? L could be ['1, 2'] (a single item list whose string item contains a comma) or any of four 2-item lists (since each item can be a string or int). The ambiguity of type is common for print of course, but the total ambiguity for number of items (since each comma could be delimiting items or part of a string item) was the decisive consideration.

提交回复
热议问题