Bright Future Bright Future - 1 year ago 88
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]


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

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

Jim Jim
Answer Source

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()


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:

[apple, kiwi, lichi]  

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download