Ruby Impressions

Fernando Pérez fperez528 at yahoo.com
Fri Jan 11 19:44:09 EST 2002


Mark McEahern wrote:

> Adam Spitz wrote:
>> class Person:
>>     def __init__(self, name, age, gender):
>>         self.name, self.age, self.gender = name, age, gender
>>         self.doSomeStuff()
>>
>> A lot of my __init__ methods look like that: they take a few
>> parameters, store them as attributes, and then maybe do some more
>> stuff. Every single time I do this, I have to write out the parameter
>> list three times - once in the method signature, once on the left side
>> of the equals sign, and once on the right side of the equals sign.

This is what I use:

def setattr_list(obj,alist,nspace):
    """Set a list of attributes for an object taken from a namespace.

    setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
    alist with their values taken from nspace, which must be a dict (something
    like locals() will often do).

    Note that alist can be given as a string, which will be automatically
    split into a list on whitespace."""

    if type(alist) is types.StringType:
        alist = alist.split()
    for attr in alist:
        val = eval(attr,nspace)
        setattr(obj,attr,val)


Use it as:

def __init__(self, name, age, gender):
  ....
  setattr_list(self, 'name age gender',locals())
  ...

For one or two things it's overkill, but nice for many.

Cheers,

f.



More information about the Python-list mailing list