Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python (retired) Inheritance __str__

I need help with a code challenge...

I can't see what I'm doing wrong on step 2. I don't think i really understand str. What's it suppose to do? Here's my code

'''from game import Game

class GameScore(Game): pass

def _str(self): return "Player 1: {}; Player 2: {}".format(self.score, self.score)

game_str.py
from game import Game

class GameScore(Game):
  pass

  def __str_(self):
    return "Player 1: {}; Player 2: {}".format(self.score, self.score)

2 Answers

Hi Tristan,

The str method requires double underscores on both sides.

Also, you have a problem with the arguments you're passing to .format

self.score is a tuple which contains both player scores. You need to be able to access each individual score.

You could access player 1's score like this `self.score[0]

Alternatively, you could simply unpack the tuple with a single asterisk in front. Like this .format(*self.score)

I forgot to answer your other question about what __str__ is supposed to do.

This method would be called for you anytime a string representation of your object is needed and it needs to return a string object.

For example, lets say you wanted to print your object. Your object needs to be converted to a string in order to be printed. So python will call your str method and the string returned from the method is what you will see get printed.

Also, once you start putting code in your class you no longer need the pass statement. This is only needed as a placeholder when your class is empty.

Thanks for the response. The tuple was my problem. I haven't taken python collections yet. I went straight to object oriented programming. Correct me if I'm wrong. A method is a function that belongs to a class?

Yes, the generally accepted terminology is that a function on its own is a function but inside of a class it's called a method.

You have a typo on the next to the last line. there needs to be a double underline after str. Like so:

__str__ 

I'll have to double check (I should know this) but I think str is an attribute not a method. Someone correct me if I'm wrong. Edit: I have been corrected.