create instance attributes for every method argument

Duncan Booth duncan.booth at invalid.invalid
Sat Jul 19 16:39:34 EDT 2008


Berco Beute <cyberco at gmail.com> wrote:

> I remember reading somewhere how to create an instance attribute for
> every method argument, but although Google is my friend, I can't seem
> to find it. This could likely be done way more elegant:
> 
>=========================
> class Test(object):
> 
>     def __init__(self, a, b, c, d, e, f):
>         self.a = a
>         self.b = b
>         self.c = c
>         self.d = d
>=========================
> 
> 2B

You *could* do something like this:

>>> class Test(object):
	def __init__(self, a, b, c, d, e, f):
		self.update(locals())

	def update(self, adict):
		for k in adict:
		    if k != 'self':
			    setattr(self, k, adict[k])

			    
>>> c = Test(1, 2, 3, 4, 5, 6)
>>> c.__dict__
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'f': 6}
>>> 

but to be honest, your original is much clearer as it expresses the 
intention without any obfuscation and as soon as you want to do anything 
more than simply copying all arguments you'll want to do the assignments 
individually anyway.



More information about the Python-list mailing list