How to set object parameters nicely?

Carl Banks pavlovevidence at gmail.com
Wed Dec 2 18:36:40 EST 2009


On Dec 2, 12:13 pm, "allen.fowler" <allen.fow... at yahoo.com> wrote:
> > >>> Is there a better way to do this?
> > >> class MyOb(object):
> > >>      def __init__(self, **kwargs):
> > >>          self.__dict__.update(kwargs)
>
> > >> ob1 = MyOb(p1="Tom", p3="New York")
> > >> ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey")
>
> > > I've tried this, but have found two issues:
>
> > > 1) I can't set default values.
> > > 2) I can't set required values.
>
> > > In both of the above cases, if theobjectis created without the
> > > "exact" dict() I expect, all the assumption my methods make about what
> > > is available in "self" fall apart.
>
> > > Perhaps, as Diez mentioned, my approach is wrong.   What would be the
> > > right thing to do in this situation?
>
> > There is no general answer to this. It depends on your actual problem.
>
> What are some of the patterns that tend to be used?

For the record, I don't really agree that a lot of parameters is code
smell.  It's maybe a red flag that you are doing too much in one
function and/or class, but nothing inherently shady.

One thing to ask yourself: are there a lot of combinations of
parameters that don't make sense?  For example, do you have a lot of
cases where, say, if one parameter is set to x, then parameters a, b,
c, and d do nothing?  That would indicate that you should break your
function/class up into smaller, more targeted parts.

However, if all your parameters are orthogonal, that is, if all or
most combinations make sense, then there's no reason ten or twenty
parameters isn't perfectly reasonable.

Whenever I have ten parameters in an __init__, I ususally just write
out the assignments, although more often than not the object's
attributes don't correspond to the parameters one-to-one, so I'd have
to write them out anyway.


Carl Banks



More information about the Python-list mailing list