On 10/03/13 19:57, Vincent Balmori wrote:
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:

[snip code]

You haven't actually asked a question here, so I don't understand what is 
giving you trouble. I'll try to guess, but please pardon me if I guess wrongly.

Have you read the error message Python gives?

__str__ returned non-string (type int)

This tells you that if __str__ returns something which is not a string, Python 
will treat it as an error. To fix that, change your __str__ method to return a 
string. Use the str() function to convert a non-string value into a string.

Is the error message not clear enough? If not, can you suggest an improvement?


Your __str__ method looks like this:

     def __str__(self):
         mood = self.boredom + self.hunger
         return mood

This is not a very good design for a __str__ function. str(some_critter) should 
return something that indicates to the reader that it is a Critter, not an 
integer. That is, something like one of these might be appropriate:

Critter(name="Fred", boredom=7, hunger=5)
<Critter object at 0xb7f744f0>
<frustrated Critter "Fred">

or similar, rather than:

12


which does not look like a Critter nor give the reader any hint at all that 
what they are seeing is a Critter.



--
Steven
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to