[Tutor] Use __str__ method for int values
Jason Friedman
jsf80238 at gmail.com
Mon Mar 11 00:44:58 CET 2013
> Thank you for the response! I next modified the __str__ so it will also
> include the values self. boredom and self. hunger. I am getting a bit
> confused with how to set up strings from within a method. It is set up like
> this:
>
> def __str__(self):
> attrs = "Hunger: ", self.hunger, "Boredom: ", self.boredom, "Mood:
> ", self.boredom + self.hunger
> return attrs
>
> When I try to execute I get this:
>
> 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 tuple)
The print statement (at least in 2.7) accepts arguments separated by
commas, but ordinary assignment gives a different result:
>>> a = "str", "ing"
>>> a
('str', 'ing')
So, you probably want something like:
attrs = "Hunger: %s Boredom: %s Mood: %s" % (self.hunger,
self.boredom, self.boredom + self.hunger)
More information about the Tutor
mailing list