is this the right way to do subclasses?

Gabriel Genellina gagsl-py at yahoo.com.ar
Thu Nov 9 03:43:34 CET 2006


At Wednesday 8/11/2006 22:35, Ben Finney wrote:

>     class Character(object):
>         stat_keys = ['strength', 'dexterity', 'intelligence']
>         def __init__(self, name, stats):
>             self.name = name
>             self.health = 10
>             self.stats = {}
>             for (key, value) in [(k, stats.get(k)) for k in stat_keys]:
>                 setattr(self, key, value)

Doesn't work, should say self.stat_keys. I prefer this other way:

=== cut ===
class Character(object):
     stat_keys = ['strength', 'dexterity', 'intelligence']
     strength = dexterity = intelligence = 0
     def __init__(self, name, **stats):
         self.name = name
         self.health = 10
         for key, value in stats.iteritems():
             if key in self.stat_keys: setattr(self, key, value)
             else: raise KeyError, "Unknown stats name: %s" % key

class Cleric(Character):
     stat_keys = Character.stat_keys + ['holyness']
     holyness = 0

c=Cleric('Fray Tuck', strength=8, dexterity=5, holyness=2)
print vars(c)
=== cut ===

This way, misspelled properties are caught, and calling interfase is 
simple too. Also, class attributes provide default instance 
attributes - you don't have to provide an explicit value. Stats names 
are extensible as shown.


-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list