jimmy Light
jimmy Light

Reputation: 107

Printing Python __str__ from an object

I have actually finished this exercise (almost) but am just stuck on a tiny problem with __str__ which is inside an object. If i do this

elif choice == "9":
    try:
        for i in sworm:
            print(i)
    except TypeError:
        None` 

Then it will only print out the details of the first object in my list (only 2 objects in there) e.g -- sworm = [crit,crit1]

When I tried this

elif choice == "9":
    try:
        print(sworm)
    except TypeError:
        None

Then I get:-

[<__main__.Critter object at 0x02B54AD0>, <__main__.Critter object at 0x02B5B190>]

Here is the first half of my Object

class Critter(object):
    """A virtual pet"""
    def __init__(self, name, hunger = random.randint(1,50), boredom = random.randint(1,50)):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom



    def __pass_time(self):
        self.hunger += 1
        self.boredom += 1

    def __str__(self):

        print ("Critter object\n")
        print (self.name)
        print (self.hunger)
        print (self.boredom)

Thanks in advance.

Upvotes: 0

Views: 3527

Answers (4)

Timothy Mugayi
Timothy Mugayi

Reputation: 1589

Alternatively if you do not want to hard code your str properties you can do it like this

def __str__(self):
    return ', '.join(['{key}={value}'.format(key=key, value=self.__dict__.get(key)) for key in self.__dict__])

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124928

A Python list always shows the contents as representations, calling repr() on the objects.

You can hook into that by specifying a __repr__ method as well. Alternatively, don't print the list directly, but only the contents:

for elem in sworm:
    print(elem)

or join them as a long string:

print(', '.join(map(str, sworm)))

Do make sure you actually return a value from your __str__ method though:

def __str__(self):
    return "Critter object\n{}\n{}\n{}".format(self.name, self.hunger, self.boredom)

because it is the return value that is printed by print().

Upvotes: 2

ersran9
ersran9

Reputation: 978

If you need the __str__ method to work, then you should return a string from it - something like this

def __str__(self):  
    return 'Critter object: %s %s %s' %(self.name, self.hunger, self.boredom)

Please read the documentation here

Upvotes: 3

kirbyfan64sos
kirbyfan64sos

Reputation: 10727

The problem is this:

    print ("Critter object\n")
    print (self.name)
    print (self.hunger)
    print (self.boredom)

See, the __str__ method shouldn't actually print anything. Instead, it should return what it wants to be printed. So, you need to do this:

    return "Critter object\n\n" + self.name + '\n' + self.hunger + '\n' + self.boredom

Upvotes: 0

Related Questions