iainking at gmail.com
Tue Apr 20 10:54:29 EDT 2010
On Apr 20, 2:43 pm, Alan Harris-Reid <aharrisr... at googlemail.com>
> 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
> 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
> 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 '_':
_ = class1
_.attr1 = 1
_.attr2 = 2
_.attr3 = 3
_.attr4 = 4
alternatively, you could use the __setattr__ method:
for attr, value in (
and to get a bit crunchy, with this your specific example can be
for i in xrange(1, 5):
class1.__setattr__('attr%d' % i, i)
More information about the Python-list