[Tutor] Use __str__ method for int values
Timo
timomlists at gmail.com
Sun Mar 10 11:23:10 CET 2013
Op 10-03-13 09:57, Vincent Balmori schreef:
> I am trying to use a __str__ method to display the values of attribute
> mood = self.hunger + self. boredom.
> When I try to execute I get this error:
>
> Traceback (most recent call last):
> File "C:/Users/Vincent/Documents/Programming Tutorials/Python
> Programming for the Absolute Beginner - Project
> Files/source/chapter08/critter_caretaker_vpb3.py", line 105, in <module>
> main()
> File "C:/Users/Vincent/Documents/Programming Tutorials/Python
> Programming for the Absolute Beginner - Project
> Files/source/chapter08/critter_caretaker_vpb3.py", line 99, in main
> print(crit)
> TypeError: __str__ returned non-string (type int)
Then return a str instead of int.
>
>
> This is the code:
>
>
> # Critter Caretaker
> # A virtual pet to care for
>
> import random
>
> class Critter(object):
>
> """A virtual pet"""
> def __init__(self, name, hunger = 0, boredom = 0):
> self.name = name
> self.hunger = hunger
> self.boredom = boredom
>
> def __pass_time(self):
> self.hunger += 1
> self.boredom += 1
>
> def __str__(self):
> mood = self.boredom + self.hunger
> return mood
Change to:
return str(mood)
Cheers,
Timo
More information about the Tutor
mailing list