Help Required to Print List

Hi, I’m new to Python and would like to get some help for below.

When i run print(products), the products are reflected as below:
[<Fruits.Product object at 0x000001D1E6FC69A0>, <Fruits.Product object at 0x000001D1E6FA84C0>, <Fruits.Product object at 0x000001D1E70033A0>, <Fruits.Product object at 0x000001D1E70039D0>]

How can I get it to appear as a list:
[[‘Orange’, ‘Australia’, 0.8], [‘Apple’, ‘Japan’, 0.7], [‘Kiwi’, ‘New Zealand’, 1.1]]
class Product:

def __init__(self, name, country, price):

    self.__name = name

    self.__category = country

    self.__price = price


def getName(self):

    return self.__name

def setName(self, name):

    self.__name = name

def getCountry(self):

    return self.__country

def setCountry(self, country):

    self.__description = country

def getPrice(self):

    return self.__price

def setPrice(self, price):

    self.__price = price

from Fruits import Product

products =

products.append(Product(“Orange”, “Australia”, 0.8))

products.append(Product(“Apple”, “Japan”, 0.7))

products.append(Product(“Kiwi”, “New Zealand”, 1.1))

def PrintProductDetails(product):

print("Name:", product.getName())

print("Country:", product.getCountry())

print("Price: ${:.2f}".format(product.getPrice()))

productName = input("Name: ")

productCountry = input("Country: ")

productPrice = float(input("Price: "))

NewProduct = Product(productName, productCountry, productPrice)




Give your class a __repr__() or a __str__() method, to control how instances are converted to string representation (including while print()ing).

Also, look at the library module pprint, to pretty-print data.

Thanks for your help.

Here’s an example:


class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def __repr__(self):
        cls_name = self.__class__.__name__
        return f"{cls_name}(name: {self._name}, age: {self._age})"

    def __str__(self):
        return repr(self)


>>> p = Person("John", 52)
>>> # __repr__
>>> p 
Person(name: John, age: 52)
>>> # __str__
>>> print(p)
Person(name: John, age: 52)

In short, the __repr__ controls the look of the object output. __str__ controls the look from print().

Thanks. This is very helpful.

1 Like