assign class variable in __init__

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Jun 8 13:58:08 EDT 2010


Peter Otten wrote:
> Jason Scheirer wrote:
>
>   
>> On Jun 8, 9:37 am, Peter Otten <__pete... at web.de> wrote:
>>     
>>> Ross Williamson wrote:
>>>       
>>>> Hi Everyone,
>>>>         
>>>> Just a quick question - Is it possible to assign class variables in
>>>> the __init__() - i.e. somthing like:
>>>>         
>>>> def __init__(self,self.source = "test", self.length = 1)
>>>>         
>>>> rather than
>>>>         
>>>> def __init__(self,source = "test", length = 1):
>>>>         
>>> No. If you are just lazy, try
>>>
>>>       
>>>>>> import sys
>>>>>> def update_self():
>>>>>>             
>>> ...     d = sys._getframe(1)
>>> ...     d = d.f_locals
>>> ...     self = d.pop("self")
>>> ...     for k, v in d.iteritems():
>>> ...             setattr(self, k, v)
>>> ...>>> class A(object):
>>>
>>> ...     def __init__(self, source="test", length=1):
>>> ...             update_self()
>>> ...     def __repr__(self):
>>> ...             return "A(source=%r, length=%r)" % (self.source,
>>> self.length)
>>> ...>>> A()
>>>
>>> A(source='test', length=1)>>> A(length=42)
>>>
>>> A(source='test', length=42)
>>>
>>> Personally, I prefer explicit assignments inside __init__().
>>>
>>> Peter
>>>       
>> Or more simply
>>
>> def __init__(self, source = "test", length = 1):
>>   for (k, v) in locals().iteritems():
>>     if k != 'self':
>>       setattr(self, k, v)
>>     
>
> The idea was that you put update_self() into a module ready for reuse...
>
> Peter
>   
still

def __init__(self, source="test", length=1):
    self.source = source
    self.length = length

is the way to go. OP's original idea is a bad idea :).
Could be a problem with hundreds of parameters, but who write 
constructors with hundreds of parameters ?

JM



More information about the Python-list mailing list