[Tutor] Class instantiation parameters

Jan Eden lists at janeden.org
Sun Aug 7 16:23:46 CEST 2005

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.

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,

Bad spellers of the world Untie!

More information about the Tutor mailing list