Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #92537

Re: Passing new fields to an object

From Peter Otten <__peter__@web.de>
Subject Re: Passing new fields to an object
Date 2015-06-12 18:17 +0200
Organization None
References <mlev91$4ji$1@speranza.aioe.org>
Newsgroups comp.lang.python
Message-ID <mailman.429.1434125838.13271.python-list@python.org> (permalink)

Show all headers | View raw


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.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Passing new fields to an object Paulo da Silva <p_s_d_a_s_i_l_v_a_ns@netcabo.pt> - 2015-06-12 16:53 +0100
  Re: Passing new fields to an object gst <g.starck@gmail.com> - 2015-06-12 09:17 -0700
    Re: Passing new fields to an object Paulo da Silva <p_s_d_a_s_i_l_v_a_ns@netcabo.pt> - 2015-06-12 19:26 +0100
  Re: Passing new fields to an object Peter Otten <__peter__@web.de> - 2015-06-12 18:17 +0200
    Re: Passing new fields to an object Paulo da Silva <p_s_d_a_s_i_l_v_a_ns@netcabo.pt> - 2015-06-12 19:34 +0100
      Re: Passing new fields to an object Peter Otten <__peter__@web.de> - 2015-06-12 21:12 +0200
        Re: Passing new fields to an object Paulo da Silva <p_s_d_a_s_i_l_v_a_ns@netcabo.pt> - 2015-06-13 04:29 +0100
  Re: Passing new fields to an object Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-06-13 01:25 +0000
    Re: Passing new fields to an object Paulo da Silva <p_s_d_a_s_i_l_v_a_ns@netcabo.pt> - 2015-06-13 04:33 +0100
    Re: Passing new fields to an object Peter Otten <__peter__@web.de> - 2015-06-13 09:49 +0200

csiph-web