简体   繁体   中英

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) eg -- 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.

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

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

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

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__])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM