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 trialMUZ140515 Herbert Chirwa
2,589 Pointsam totally confused with stage four, went over the tutorial but l still don't get whats required of the last challenge
can you explain what the last challenge requires
from character import Character
class Warrior(Character):
weapon = "sword"
def rage(self):
self.attack_limit = 20
def some_method(self):
return self.a_value
def print(self):
string = "{}, <{}>, <{}>".format(string, weapon, rage())
return string
1 Answer
Andrei Fecioru
15,059 PointsThe challenge requires you to implement in you Warrior
class one of those "special" methods that start with a double underscore. In this particular case, we are talking about the __str__
method which provides an automatic string representation for your class. This method will be invoked automatically whenever such a representation is required by the usage context of your objects (example: passing a Warrior
object as an argument to the print
function). As far as I remember this technique is mentioned in the course.
One variation of the code that passes the challenge would be:
from character import Character
class Warrior(Character):
weapon = "sword"
def rage(self):
self.attack_limit = 20
def __str__(self):
return "Warrior, {}, {}".format(self.weapon, self.attack_limit)
With this code in place, if you pass an instance of the Warrior
class to the print
function, the __str__
method will be automatically invoked on that object and the string returned by that method invocation would be used and printed out at the console.
w = Warrior()
# this will print out: Warrior, sword, 20"
print(w)
It is good practice to implement the __str__
method for your custom objects and provide a human-readable string representation for them.
Hope this helps.