What's the best way to write this base class?
Mel
mwilson at the-wire.com
Sat Jun 18 10:22:59 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
>
> 2)
> class Character:
> base_health = 50
> base_resource = 10
> def __init__(self, name):
> self.name = name
> self.health = base_health
> self.resource = base_resource
>
> 3)
> BASE_HEALTH = 50
> BASE_RESOURCE = 10
> class Character:
> def __init__(self, name):
> self.name = name
> self.health = BASE_HEALTH
> self.resource = BASE_RESOURCE
For completeness, there's also 4)
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Character (object):
... health = 50
... def __init__ (self, name):
... self.name = name
... print self.name, self.health
...
>>> Character ('Eunice')
Eunice 50
where the class attribute is used until it's overridden in the instance.
Mel.
More information about the Python-list
mailing list