Bright Future Bright Future - 3 months ago 7
Python Question

How to print out elements of a class

I just got started with python, now I need to print out the names of elements/objects/instances of a class, this is my code:

class Delicious :
sweet = 0
sour = 0

apple = Delicious()
kiwi = Delicious()
litchi = Delicious()

bracket = [apple, kiwi, lichi]

print(bracket)


I ran it in the terminal, it prints out:
[<main.Delicious object at 0x1019d9940>, <main.Delicious object at 0x1019d9978>, <main.Delicious object at 0x1019d99b0>]
how do I make it print
apple
kiwi
litchi
?

The other answers are too hard for me, can somebody answer it simply?

Jim Jim
Answer

The way to get this to work is by grabbing the instances name from globals() and returning it from __str__:

class Delicious : 
    sweet = 0
    sour = 0

    def __str__(self):
        for k, v in globals().items():
            if v == self:
                return k

    def __repr__(self):
        return str(self)

Now printing will return the name as you defined it:

apple = Delicious()

print(apple)
apple

Printing a list that contains your objects will call their __repr__, so you can either also define __repr__ to return __str__s result, or call print(*bracket) to unpack the list in the print call which uses their __str__ function:

print(bracket)
[apple, kiwi, lichi]  

print(*bracket)
apple, kiwi, lichi

But this make 0 practical sense, in Python names are just labels assigned to objects, by using print and printing the name you get no information about the underlying object.

Comments