How to set object parameters nicely?

Diez B. Roggisch deets at nospam.web.de
Tue Dec 1 18:36:04 EST 2009


allen.fowler schrieb:
>>> 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?

There is no general answer to this. It depends on your actual problem.

Diez



More information about the Python-list mailing list