[Tutor] Use __str__ method for int values
Vincent Balmori
vincentbalmori at yahoo.com
Sun Mar 10 09:57:16 CET 2013
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)
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
@property
def mood(self):
unhappiness = self.hunger + self.boredom
if unhappiness < 5:
m = "happy"
elif 5 <= unhappiness <= 10:
m = "okay"
elif 11 <= unhappiness <= 15:
m = "frustrated"
else:
m = "mad"
return m
def talk(self):
print("I'm", self.name, "and I feel", self.mood, "now.\n")
self.__pass_time()
def eat(self, food = 4):
food = int(input("How much do you want to feed?: "))
while food > 5:
food = int(input("That's too much! How much do you want to feed?: "))
print("Brruppp. Thank you.")
self.hunger -= food
self.boredom += int(food * random.randint(0,3))
if self.hunger < 0:
self.hunger = 0
self.__pass_time()
def play(self, fun = 4):
fun = int(input("How long do you want to play?: "))
while fun > 5:
fun = int(input("That's too long! How long do you want to play?: "))
print("Wheee!")
self.boredom -= fun
self.hunger += int(fun * random.randint(0,3))
if self.boredom < 0:
self.boredom = 0
self.__pass_time()
def main():
crit_name = input("What do you want to name your critter?: ")
crit = Critter(crit_name)
choice = None
while choice != "0":
print \
("""
Critter Caretaker
0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
# listen to your critter
elif choice == "1":
crit.talk()
# feed your critter
elif choice == "2":
crit.eat()
# play with your critter
elif choice == "3":
crit.play()
# play with your critter
elif choice == "4":
print(crit)
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
main()
("\n\nPress the enter key to exit.")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130310/d9b1a287/attachment-0001.html>
More information about the Tutor
mailing list