[Tutor] Class instantiation parameters

Jan Eden lists at janeden.org
Sun Aug 7 22:08:25 CEST 2005

Hi Kent, hi Alan,

Alan G wrote on 07.08.2005:

>> page = Show(type=type, id=id)
>> class Show:
>>     def __init__(self, type, id):
>>         self.id = id
>> ...
>>        return self
>First a couple of comments.
>You don't need to return self from __init__.
>You can only instantiate Show *after* you've defined it.
Right - I still think along the lines of Perl subroutines used as methods.

>**args is indeed the solution to this so you may have 
>figured it all out already, but your terminology is
>slightly confusing (because while it is strictly valid 
>in what it says, but so unlikely in its meaning, that 
>I suspect you are getting some of your terms mixed up?)

The idea is to pass keyword arguments to an instantiation function and automatically create instance attributes for each keyword argument. My apologies if I still mix up some well-defined terms in Python.

Kent Johnson wrote on 07.08.2005:

>for i in parameters.keys(): setattr(self, i, parameters[i])
>or for k, v in parameters.items(): setattr(self, k, v)
>The problem with this approach is that the function can be called
>with any number of arguments - you lose the limited type safety you
>get from declaring the arguments in the def - and it only works with
>keyword arguments, not positional arguments.
Thanks! The setattr function is exactly what I was looking for. I should not need to worry about type safety, because the instance is instantiated from within a script after making sure that id is an integer and type is a string from a predefined set of strings.

Now I'll see if I understand the practical difference between items() and iteritems() - the Python tutorial uses iteritems() in such a context.

>If you really just want a dictionary, maybe you should just use one?
>If you want the syntactic sugar of attribute access instead of
>dictionary lookup you could make a dict subclass that supports that.

I do not really want a dictionary - I just want to pass some named parameters and turn them into attributes. But I will check out the recipes anyway.

This is a really friendly and helpful list. Thanks again for all your help.

- Jan
Mac OS X. Because making Unix user-friendly is easier than debugging Windows.

More information about the Tutor mailing list