By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,798 Members | 1,403 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,798 IT Pros & Developers. It's quick & easy.

create instance attributes for every method argument

P: n/a
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
Jul 19 '08 #1
Share this Question
Share on Google+
3 Replies

P: n/a
Berco Beute 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
IMHO you can't do much better than that with positional arguments, but you can
if they are keyword arguments.

class foo(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)

-Larry

Jul 19 '08 #2

P: n/a
Berco Beute <cy*****@gmail.comwrote:
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.
Jul 19 '08 #3

P: n/a
Berco Beute 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
=========================
http://code.activestate.com/recipes/280381/

Personally, I prefer to spell it out like you did above.

Peter
Jul 19 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.