Back

Printing all the details in an object

Introduction
When we tried to print an object using print (monster1), it didn't do what we wanted it to do. It told us where the object was in memory but didn't tell us about any of the attributes of the object. To do that, we can make use of another special method called __str__ and we will see how that works below.

The special __str__ method
Add the extra method def __str__ to your code. It should look like this:

str

The __str__ method
We have added another, special method called __str__ starting on line 11. As with all methods, the first parameter must be self, but we don't need to pass any other data to this method unlike when we need to create a new monster. What we are going to do in this method is to create one string of information, by concatenating all of the attributes in an object. We will use a variable called summary to hold the string and then return that variable when the method is called. 

On line 12, we put "Name" and then concatenated it using the + symbol (concatenate means 'add strings together') to the self.name attribute. We will concatenate that to '\n' which will start a new line when the final details are displayed on the screen. Next, we have the \ symbol, which allows us to go onto the next line in the code we are writing, to help us layout the code a little better. Then we concatenate the other details.

Checking what data type something is
The only extra thing to mention is the use of str in str(self.strength) for example. We had to do this for self.strength because it is an integer. We have to convert it into a string to be able to do string concatenation. You can always find out what data type something is using the type keyword and you can see that I have used this on lines 30 and 31.

Running the code
If you ever need to print out all of the details in an object, you can now do it simply by printing the object, as on lines 34 and 35.

Try out these questions.
1) Remove str from line 13 and run the code. What happened?
2) Remove '\n' from line 12 and run the code. What happened?
3) Remove the \ from the end of line 14 and run the code. What happened?
4) Change line 34 and 35 so that it reads:

print (monster1.__str__())
print (monster2.__str__())

Run the code. What happened? Can you explain why it still works as it should?
5)
Change __str__ so that each of a monster's attributes is on a new line e.g. 

Name = Gregor
Strength = 6
Wisdom = 7
Magic = 3

and then test it works.

Back