Add New Attributes

Set foreign values of corresponding keys as new attributes in the sent self instance, with the setattr( ) function


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 battlecry(self):
    return self.sound.upper()

Testing

>>> from monster import Monster 
>>> jubjub = Monster()
>>> jubjub.hit_points
1 
>>> jubjub.color
'blue'
>>> jabberwock = Monster(color='blue', sound='whiffling', hit_points=500, adjective='manxsome')
>>> jabberwock.hit_points
500
>>> jabberwock.adjective
'manxsome'

Subclasses

Goblin is a Subclass of Monster. To pass the code without doing anything we use the keyword pass.

class Goblin(Monster):
  pass

Our original class Monster implicitly has a parent class too, called “object”.
You’ll need to make it explicit only if you want your code to work on Python 2 and Python 3 together.

class Monster(object):
  max_hit_points = 3 
  max_experience = 2 
  sound = 'squeak'
>>> from monster import Goblin
>>> azog = Goblin()
>>> azog.hit_points
2 
>>>

Combining classes using inheritance gives a great way to have your base class provide the default generic attributes in methods, while creating subclasses to handle specific scenarios.

Adding some more subclasses:

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'
>>> import monster 
>>> azog = monster.Goblin()
>>> snaga = monster.Troll()
>>> pete = monster.Dragon()
>>> pete.hit_points
10