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

Ethan Furman ethan at stoneleaf.us
Sat Jun 18 11:37:00 EDT 2011


John Salerno wrote:
> 1)
> class Character:
> 
>     def __init__(self, name, base_health=50, base_resource=10):
>         self.name = name
>         self.health = base_health
>         self.resource = base_resource

You said above that health and resource will never be explicitly passed, 
yet here you have allowed for that possibility.  If you are going to 
have mosters, etc, also inherit from Character, with different health 
and resources, I would go this route with one change:

     def __init__(self, name, base_health, base_resoures):

and always specify those numbers on creation.


> 2)
> class Character:
> 
>     base_health = 50
>     base_resource = 10
> 
>     def __init__(self, name):
>         self.name = name
>         self.health = base_health
>         self.resource = base_resource

You do not need to assign health and resource here -- they are already 
assigned on the class, so the instance will see them automatically. 
When a change is made, the instance will automagically get its own copy.


> 3)
> BASE_HEALTH = 50
> BASE_RESOURCE = 10
> 
> class Character:
> 
>     def __init__(self, name):
>         self.name = name
>         self.health = BASE_HEALTH
>         self.resource = BASE_RESOURCE

If *all* characters (player, non-player, monster, etc) will have the 
same base health and resources then this is fine -- otherwise I would 
use option 1.

~Ethan~



More information about the Python-list mailing list