Parameter lists

rzed rzantow at gmail.com
Sun Feb 4 12:20:35 EST 2007


Mizipzor <mizipzor at gmail.com> wrote in
news:mailman.3533.1170607508.32031.python-list at python.org: 

> Consider the following snippet of code:
> 
> ==========================
> 
> class Stats:
>     def __init__(self, speed, maxHp, armor, strength,
>     attackSpeed, imagePath): 
>         self.speed = speed
>         self.maxHp = maxHp
>         self.armor = armor
>         self.strength = strength
>         self.attackSpeed = attackSpeed
>         self.originalImage = loadTexture(imagePath)
> 
> ==========================
> 
> I little container for holding the stats for some rpg character
> or something. Now, I dont like the looks of that code, there are
> many function parameters to be sent in and if I were to add an
> attribute, i would need to add it in three places. Add it to the
> function parameters, add it to the class and assign it.
> 
> Is there a smoother way to do this? There usually is in python,
> hehe. I recall when reading python tutorials that you could do
> something like this:
> 
> foo(*list_of_parameters):
> 
> To send many parameters as a list or a tuple. Then I could
> assign them like this:
> 
> class Stats:
>     def __init__(self, *li):
>         self.speed = li[0]
>         self.maxHp = li[1]
>         (...)
> 
> Or maybe there is an even niftier way that lets me iterate
> through them? Hmm... but that may lead to that I need to store
> them in a way that makes it cumbersome to access them later.
> 
> Any comments and/or suggestions are welcome!  :)
> 

I often use something like this, based on a Martellibot posting:

>>> class Stats(dict):
...     def __init__(self, *args, **kwds):
...         self.update(*args)
...         self.update(kwds)
...     def __setitem__(self, key, value):
...         return super(Stats, self).__setitem__(key, value)
...     def __getitem__(self, name):
...         try:
...             return super(Stats, self).__getitem__(name)
...         except KeyError:
...             return None
...     __getattr__ = __getitem__
...     __setattr__ = __setitem__
...
>>> m = dict(a=1,b=22,c=(1,2,3))
>>> p = Stats(m,x=4,y=[5,9,11])
>>> p.y
[5, 9, 11]
>>> p['y']
[5, 9, 11]

-- 
rzed



More information about the Python-list mailing list