Passing new fields to an object

Peter Otten __peter__ at web.de
Fri Jun 12 12:17:09 EDT 2015


Paulo da Silva wrote:

> I would like to do something like this:
> 
> class C:
> def __init__(self,**parms):
> ...
> 
> c=C(f1=1,f2=None)
> 
> I want to have, for the object
> self.f1=1
> self.f2=None
> 
> for an arbitrary number of parameters.
> 
> What is the best way to achieve this?

Use a dict ;)

While I'd recommend that you spell out the possible arguments here is one 
way to not obey my advice:

>>> import types
>>> class C(types.SimpleNamespace):
...     pass
... 
>>> c = C(f1=1, f2=None)
>>> c
C(f1=1, f2=None)

If you want to do it manually you can either use

for name, value in parms.items():
    setattr(self, name, value)

or the less general

self.__dict__.update(parms)

Again, if you don't know the names in advance the appropriate data structure 
is a dict.




More information about the Python-list mailing list