refactoring so that multiple changes can be made with one variable?

John Salerno johnjsal at NOSPAMgmail.com
Tue Nov 14 10:41:53 EST 2006


My code is below. For now I'm focusing on the lines where health (and 
armor) are increased in each character class. Let's say I decided to 
change the amount of increase in the future. As it is now, I'd have to 
go to each character class and change the number so that each is still 
in a good relation to the other (right now: 3, 2, 1; later: perhaps 4, 
3, 2, 1, if I added a new class -- i.e., change Fighter from 3 to 4, 
Thief from 2 to 3, in other words increase them all by 1). So instead of 
changing each one, is there a simple, clean way of just changing a 
single number so that this change is reflected in all classes? Hope that 
makes sense.



class Character(object):
     def __init__(self, name, strength, dexterity, intelligence):
         self.name = name
         self.health = 10
         self.armor = self.attack = self.defense = self.magic_attack = \
             self.magic_defense = 0
         self.strength = strength
         self.dexterity = dexterity
         self.intelligence = intelligence
         self.adjust_attributes()

     def adjust_attributes(self):
         pass


class Fighter(Character):
     def adjust_attributes(self):
         self.health += 3
         self.armor += 3
         self.attack += 2
         self.defense += 2
         self.strength += 1


class Thief(Character):
     def adjust_attributes(self):
         self.health += 2
         self.armor += 2
         self.attack += 1
         self.defense += 1
         self.magic_defense += 1
         self.dexterity += 1


class Mage(Character):
     def adjust_attributes(self):
         self.health += 1
         self.armor += 1
         self.magic_attack += 2
         self.magic_defense += 2
         self.intelligence += 1



More information about the Python-list mailing list