[Tutor] Class instantiation parameters

Kent Johnson kent37 at tds.net
Sun Aug 7 16:45:21 CEST 2005


Jan Eden wrote:
> 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.

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.

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. The comments to this recipe show one way to do it:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668

This recipe is more complete but has different initialization semantics that what you want:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389916

You might also be interested in this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/218485

Kent



More information about the Tutor mailing list