Code redundancy
Alan Harris-Reid
aharrisreid at googlemail.com
Tue Apr 20 17:50:10 EDT 2010
Iain King wrote:
> On Apr 20, 2:43 pm, Alan Harris-Reid <aharrisr... at googlemail.com>
> wrote:
>
>> Hi,
>>
>> During my Python (3.1) programming I often find myself having to repeat
>> code such as...
>>
>> class1.attr1 =
>> class1.attr2 =
>> class1.attr3 =
>> class1.attr4 =
>> 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 =
>> .attr2 =
>> .attr3 =
>> .attr4 =
>> etc.
>> endwith
>>
>> Is there any equivalent to this in Python?
>>
>> Any help would be appreciated.
>>
>> Alan Harris-Reid
>>
>
> The pythonic equivalent of VB 'with' is to assign to a short variable
> name, for example '_':
>
> _ =lass1
> _.attr1 =
> _.attr2 =
> _.attr3 =
> _.attr4 =
>
> alternatively, you could use the __setattr__ method:
>
> for attr, value in (
> ('attr1', 1),
> ('attr2', 2),
> ('attr3', 3),
> ('attr4', 4)):
> class1.__setattr__(attr, value)
>
> and to get a bit crunchy, with this your specific example can be
> written:
>
> for i in xrange(1, 5):
> class1.__setattr__('attr%d' % i, i)
>
> Iain
Hi Iain, thanks for the reply,
Like the _. prefix idea - I didn't know _ could be used as a variable name.
>for i in xrange(1, 5):
> class1.__setattr__('attr%d' % i, i)
Good solution if the values matched the attribute names, but
unfortunately they don't. That was just a (bad) example to illustrate
my problem.
Regards,
Alan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100420/52f9bf99/attachment-0001.html>
More information about the Python-list
mailing list