is this the right way to do subclasses?

Peter Otten __peter__ at web.de
Wed Nov 8 22:08:47 CET 2006


John Salerno wrote:

> Peter Otten wrote:
> 
>> One way to avoid the repetition:
>> 
>> class Character(object):
>>     def __init__(self, name, strength, dexterity, intelligence):
>>         self.name = name
>>         self.health = 10
>>         self.strength = strength
>>         self.dexterity = dexterity
>>         self.intelligence = intelligence
>>         self.fix_attributes()
>> 
>> class Fighter(Character):
>>     def fix_attributes(self):
>>         self.health += 2
>>         self.strength += 1
>> 
>> You may need a no-op implementation of fix_attributes() in the Character
>> class.

> But how does this take care of the initialization of the stats? I won't
> be able to use Fighter to create a character without doing everything in
> Character, right?

Try it: Fighter(...) will implicitly call Character.__init__(...).

Peter



More information about the Python-list mailing list