Variable interpolation or indirection for instance attributes

Mike Meyer mwm at mired.org
Wed Feb 19 17:26:48 EST 2003


google at moodring.com (Rich) writes:

> Not trying to do anything evil or weird ... just a parallel to what I
> would do in Perl with:

Ah, but trying to write Perl in Python *is* weird, and maybe even
evil. Not because there's anything wrong with writing Perl, but
because Python isn't Perl.

> sub initialize {
>   my $self     = shift;    
>   my %address  = @_;         
> 
>   my @addresskeys   = qw ( Street City State Zip );
>   map { $self->{$_} = $address{$_} }  @addresskeys;
> }

I think the pythonic way to do that is:

        def __init__(self, street, city, state, zip):
            self.Street, self.City, self.State, self.Zip = street, city, state, zip

Others may well disagree. For instance, you can collect all the
arguments in a list, which gets you closer to what you wrote:

        def __init__(self, *address) self.Street, self.City,
            self.State, self.Zip = address

But then when someone puts in the wrong number of arguments, you get
an exception at the assignment instead of at the function call. I
prefer the former, even though it is more verbose. Given the nature of
Perl, I suspect you didn't get an error at all in perl, but instead
got default values. You can mimic that with keyword arguments.

        <mike




More information about the Python-list mailing list