aharrisreid at googlemail.com
Tue Apr 20 19:04:49 EDT 2010
Chris Rebert wrote:
> On Tue, Apr 20, 2010 at 2:59 PM, Alan Harris-Reid
> <aharrisreid at googlemail.com> wrote:
>> Stefan Behnel wrote:
>>> 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
>>>> 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?
>>> 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
>> 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
>> 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)?
> Why are you against passing them as parameters?
> If your constructor would have a lot of parameters, it may be a sign that:
> (A) you have some Data Clumps
> (http://martinfowler.com/bliki/DataClump.html) among the parameters
> that ought to be made into full objects
> (B) your class is doing too many things and needs to be split into
> multiple classes
> Yay Refactoring!
Hi Chris, thanks for the reply.
Nothing against passing the values as parameters, but it can start to
look a bit ugly if there are too many of them. Which brings me to your
2nd point of maybe refactoring the passing/receiving of parameters so
that I can use an object with attributes instead of individual variable
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list