I’m trying to better understand the proper usage of the __str__ function.
Let’s say I have a very simple class called Character for use in a game that looks like this:
class Character(object):
""" A game character. """
def __init__(self, name):
self.name = name
self.poisoned = False
self.strength = random.randrange(10, 20)
self.max_strength = self.strength
self.dexterity = random.randrange(10, 20)
self.max_dexterity = self.dexterity
self.hit_points = 100
self.spell_points = 100
self.weapon = []
self.spell = []
self.items = []
self.aura = []
self.xp = 0
Prior to learning about the __str__ function, I would have defined a method of the class called print_stats(self) that would print the character stats via Character.print_stats(). After learning about __str__ though it seemed like this was a function for defining and displaying the statistics of an object, similar to what I would do with print_stats(self)… but in playing with it and learning that the returned value must be a string and not contain integers, it appears my assumption is wrong.
So now my question is what are some examples of good usage of the __str__? Would the example I provide benefit from using that function?
Printing stats is a fine use of
__str__(). Simply use string formatting to return a single string value: