[Tutor] Class instantiation parameters

Jan Eden lists at janeden.org
Sun Aug 7 10:14:36 CEST 2005


after using Perl for some years for simple scripting tasks, one of my programs reached a size where an OO design is appropriate. So I rewrote the program using OO techniques in Perl. Because I am not entirely satisfied with the implementation, I decided port the program to Python.

The first thing I'd like to sort out are the parameters on class invocation. In Perl, I did (... for lines left out):

my $page = Show->new(type => $type, id => $id);

package Show;
sub new {
    my $class = shift;
    my $self = { @_ };
    bless $self, $class;
    return $self;

making use of the relatively liquid border between hashes (dictionaries) and arrays (lists).

In Python, I would do:

page = Show(type=type, id=id)

class Show:
    def __init__(self, type, id):
        self.id = id
        self.type = type
        return self

For two parameters, this is relatively simple. But if I have for example 10 parameters on instantiation, assigning each value the the class object manually will be really clumsy.

So how can I add the values of all the paramaters to my class instance in one step?

Thanks in advance,

Imagine if every Thursday your shoes exploded if you tied them the usual way. This happens to us all the time with computers, and nobody thinks of complaining. - Jeff Raskin

More information about the Tutor mailing list