It is a special method that is called whenever something is converted into a string.
>>> from monster import Dragon >>> draco = Dragon() >>> print(draco) <monster.Dragon object at 0x7f351cd3518a>
__str__( ) , __class__.__name__
# [moster.py]:
import random
COLORS = ['yellow', 'red', 'blue', 'green']
class Monster:
min_hit_point = 1
max_hit_point = 1
max_experience = 1
min_experience = 1
weapon = 'sword'
sound = 'roar'
def __init__(self, **kwargs):
self.hit_points = random.randint(self.min_hit_points, self.max_hit_points)
self.experience = random.randint(self.min_experience, self.max_experience)
self.color = random.choice(COLORS)
for key, value in kwargs.items():
setattr(self, key, value)
def __str__(self):
return '{} {}, HP: {}, XP: {}'.format(self.color.title(),
self.__class__.__name__ # Gets class name
self.hit_points,
self.experience)
def battlecry(self):
return self.sound.upper()
class Goblin(Monster):
pass
class Troll(Monster):
min_hit_points = 3
max_hit_points = 5
min_experience = 2
max_experience = 6
sound = 'growl'
class Dragon(Monster):
min_hit_points = 5
max_hit_points = 10
min_experience = 6
max_experience = 10
sound = 'raaaaaar'
Test monster.py
>>> from monster import Dragon >>> draco = Dragon() >>> print(draco) Blue Dragon, HP: 5, XP: 6
EXERCISE
Game score is a tuple where the first item is the score of Player 1, and the second item is the score of Player 2.
from game import Game
class GameScore(Game):
def __str__(self):
return "Player 1: {}; Player 2: {}".format(*self.score)