Ruby Impressions

Donn Cave donn at drizzle.com
Sat Jan 12 02:40:08 EST 2002


Quoth adamspitz at bigfoot.com (Adam Spitz):
...
| But I suppose my original post wasn't very clear. Here's the problem
| that we were solving:
|
| 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.
|
| I'd like to be able to tell Python, "Make me an __init__ method that
| takes these three parameters, stores them as attributes, and then does
| this other stuff." And I'd like to be able to do it in a way that
| doesn't force me to repeat the parameter list three times. Ideally,
| it'd look something like this (if I were allowed to make up any syntax
| I wanted):
|
| class Person:
|     init_attributes("name", "age", "gender"):
|         self.doSomeStuff()

Would something like this suffice?

class IV:
	"Mixin class for initialization from a tuple of values."
	membernames = ()
	def initialize_members(self, av):
		count = min(len(av), len(self.membernames))
		for i in range(len(av)):
			setattr(self, self.membernames[i], av[i])

class Person(IV):
	membernames = ('name', 'age', 'gender')
	MALE = 'Male'
	def __init__(self, *av):
		self.initialize_members(av)

p = Person('Melvin', 23, Person.MALE)

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list