How to set object parameters nicely?

allen.fowler allen.fowler at yahoo.com
Wed Dec 2 15:13:23 EST 2009


> >>> 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.
>
> Diez

What are some of the patterns that tend to be used?

-- AF



More information about the Python-list mailing list