What's the best way to write this base class?

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Sat Jun 18 09:37:56 EDT 2011


On 18 juin, 13:24, Tim Chase <python.l... at tim.thechases.com> wrote:
> On 06/18/2011 05:55 AM, bruno.desthuilli... at gmail.com wrote:
>> > On 18 juin, 06:17, John Salerno<johnj... at gmail.com>  wrote:
> >> class Character:
>> >>      base_health = 50
> >>      base_resource = 10
>> >>      def __init__(self, name):
> >>          self.name = name
> >>          self.health = base_health
> >>          self.resource = base_resource
>> > Did you at least tried this one ? Hint: it won't work.
>> If you want it, you can use
>>    self.health = Character.base_health
>> Though I'd treat them as semi-constants and capitalize them like
> your 3rd case:
>>    class Character(object):
>      BASE_HEALTH = 50
>      ...
>      def __init__(...):
>        ...
>        self.health = Character.BASE_HEALTH
>
If you go that way, then using polymorphic dispatch might (or not,
depending on the game's rules <g>) be a good idea:
class Character(object):
 BASE_HEALTH = 50
 ...
 def __init__(self, name):
 ...
 self.health = type(self).BASE_HEALTH
This would allow different Character subclasses to have different
BASE_HEALTH etc..., defaulting to the base class values.


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /