0

Here's the code made me confused:

class Fruit():
    def __init__(self, name, price):
        self.name = name
        self.price = price
    def __str__(self):
        return "%s is %d" % (self.name,self.price)

L = [Fruit("Cherry", 10), Fruit("Apple", 5), Fruit("Blueberry", 20)]
print(Fruit("Cherry", 10))
print(L)

OUTPUT:
Cherry is 10
[<__main__.Fruit object>, <__main__.Fruit object>, <__main__.Fruit object>]

Since I've defined the str method, so I can print out an instance as "Cherry is 10", but when I print the list L, those instances in the list couldn't be printed out.

I'm wondering what's the logic behind it. Is it because the print() doesn't read the sub layer of the list?

Sylvia
  • 11
  • 2
  • 1
    When printing the list, Python is calling the `__repr__` method for objects, not `__str__`. [This question](https://stackoverflow.com/questions/1436703/what-is-the-difference-between-str-and-repr) may be of interest. – larsks Feb 22 '23 at 01:57

0 Answers0