what is the idiom for copy lots of params into self?
Steve Holden
steve at holdenweb.com
Wed Jan 10 19:03:26 EST 2007
Jean-Paul Calderone wrote:
> On 10 Jan 2007 14:46:54 -0800, Emin <emin.shopper at gmail.com> wrote:
>> Dear Experts,
>>
>> When writing large classes, I sometimes find myself needing to copy a
>> lot of parameters from the argument of __init__ into self. Instead of
>> having twenty lines that all basically say something like self.x = x, I
>> often use __dict__ via something like:
>>
>> class example:
>> def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n):
>> for name in
>> ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']:
>> self.__dict__[name] = locals()[name]
>>
>> This saves a lot of code and makes it easier to see what is going on,
>> but it seems like there should be a better idiom for this task. Any
>> suggestions?
>
> I use a helper, like
>
> http://divmod.org/trac/browser/trunk/Epsilon/epsilon/structlike.py#L35
>
If you don't want to go that far then this might give you an idea or two:
>>> class example:
... def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n):
... for name in inspect.getargspec(example.__init__)[0]:
... print name
...
>>> x = example(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
self
a
b
c
d
e
f
g
h
i
j
k
l
m
n
>>>
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
More information about the Python-list
mailing list