How to set object parameters nicely?
MRAB
python at mrabarnett.plus.com
Tue Dec 1 18:13:55 EST 2009
allen.fowler wrote:
> Hello,
>
> I've got a bunch of code that looks something like:
>
> class MyOb(object):
> def __init__(self, p1=None, p2=None, p3=None, ...):
> self.p1 = p1
> self.p2 = p2
> self.p3 = p3
> self.pN = ...
>
>
> ob1 = MyOb(p1="Tom", p3="New York")
> ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey")
>
> ... and so on.
>
> This is fine for only a few parameters, but it's very ugly and a lot
> of duplicate typing once I've got 10+ parameters and 5 kinds of
> objects.
>
> 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")
More information about the Python-list
mailing list