Code redundancy

Alan Harris-Reid aharrisreid at googlemail.com
Tue Apr 20 23:59:11 CEST 2010


Stefan Behnel wrote:
> <div class="moz-text-flowed">Alan Harris-Reid, 20.04.2010 15:43:
>> During my Python (3.1) programming I often find myself having to repeat
>> code such as...
>>
>> class1.attr1 = 1
>> class1.attr2 = 2
>> class1.attr3 = 3
>> class1.attr4 = 4
>> etc.
>>
>> Is there any way to achieve the same result without having to repeat the
>> class1 prefix? Before Python my previous main language was Visual
>> Foxpro, which had the syntax...
>>
>> with class1
>> .attr1 = 1
>> .attr2 = 2
>> .attr3 = 3
>> .attr4 = 4
>> etc.
>> endwith
>>
>> Is there any equivalent to this in Python?
>
> There's more than one way to do this, depending on your actual needs 
> and the source of the attributes. I assume this is done in __init__?
>
> This might work for you:
>
>     self.__dict__.update(attr1=1, attr2=2, attr3=3, attr4=4)
>
> You should also think once more about the use of the code you 
> presented above, having to set all those attributes may have a little 
> smell. Maybe that's totally ok, but since you mention that you "often" 
> find yourself doing the above, you may also have a mental design 
> problem somewhere. We can't tell unless you provide a more concrete 
> example than what you show above.
>
> Stefan
Hi Stefan, thanks for the reply.

The code is not usually in class.__init__ (otherwise I would have used 
the self. prefix), but I like your self.__dict__.update(...) solution 
and I'll try and remember it.

The code I was thinking of goes something like as follows (don't have a 
specific example to hand, but the principal is the same)...

NewClass = BaseClass()
NewClass.attr1 = value1
NewClass.attr2 = value2
NewClass.attr3 = value3
etc.

So if there are more than a couple of attributes to set for a class 
instance, how would you approach it (short of passing the values as 
parameters to BaseClass)?

Regards,
Alan



More information about the Python-list mailing list