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

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to