Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better understanding of __str__ usage

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?

like image 950
Vin Breau Avatar asked Nov 27 '12 21:11

Vin Breau


People also ask

What is the purpose of the __ str __ method?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.

What is the use of __ call __ in Python?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

Should I use repr or str?

str() is used for creating output for end user while repr() is mainly used for debugging and development. repr's goal is to be unambiguous and str's is to be readable.


2 Answers

Printing stats is a fine use of __str__(). Simply use string formatting to return a single string value:

def __str__(self):
    return ('Name: {name}\n'
        'Poisoned: {poisoned}\n'
        # etc.
    ).format(**self.__dict__)
like image 54
Martijn Pieters Avatar answered Oct 05 '22 07:10

Martijn Pieters


__str__ exists so that you can get a string representation of your object. Note that the builtin print function/statement calls str implicitly:

print 1

is exactly the same as:

print str(1)

which is the same as:

print (1).__str__()

because print calls __str__ implicitly.


Now to your class -- The most natural thing to do is if you would have written:

print self.foo,self.bar,self.baz

You could define __str__ as:

def __str__(self):
    return " ".join(str(x) for x in (self.foo,self.bar,self.baz))

Now to print your character's stats, you'd just do:

print character  #same as `print str(character)` :)

Usually this is a little limited, so there exists string formatting via .format (or old "sprintf" style formatting using the % operator).

def __str__(self):
    return "my {foo} went to the {baz} to buy a {bar}".format(foo=self.foo,
                                                              baz=self.baz,
                                                              bar=self.bar)
like image 21
mgilson Avatar answered Oct 05 '22 07:10

mgilson