How to set object parameters nicely?

allen.fowler allen.fowler at yahoo.com
Tue Dec 1 18:26:32 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 the object is 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?

-- AF



More information about the Python-list mailing list