Hi Kent,

Kent Johnson wrote on 07.08.2005:

>>So how can I add the values of all the paramaters to my class
>>instance in one step?
>
>There was recently a long discussion of this on comp.lang.python.
>http://groups.google.com/group/comp.lang.python/browse_frm/thread/
>7346ad00a14e821a/9dc993d295475cac?q=locals()&rnum=15&hl=en#
>9dc993d295475cac

Thanks for this. I thought I could do it with the help of **args, but maybe I 
still think too much in Perl terms. It's a bit unexpected that this task asks 
for such an indirect approach.

In Perl, where my class instances are usually nothing but (blessed) hash 
references, a more verbose version of my actual method would read:

package NewClass;
...
sub new {
    my $self = shift;
    my $parameters = { @_ };
    for (keys %$parameters) { $self->{$_} = $parameters->{$_};
}

My idea was to transfer the same technique to Python like this:

class NewClass:
    def __init__(self, **parameters):
        for i in parameters.keys(): self.i = parameters[i]

But the assignment in the for loop obviously does not work with instance 
attributes. I will have to read up some more about instance attributes.

Thanks again,

Jan
-- 
Bad spellers of the world Untie!
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to