Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #92548
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: Passing new fields to an object |
| Date | 2015-06-12 21:12 +0200 |
| Organization | None |
| References | <mlev91$4ji$1@speranza.aioe.org> <mailman.429.1434125838.13271.python-list@python.org> <mlf8mu$ro2$1@speranza.aioe.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.436.1434136357.13271.python-list@python.org> (permalink) |
Paulo da Silva wrote: > On 12-06-2015 17:17, Peter Otten wrote: >> Paulo da Silva wrote: >> > ... > >> >>>>> import types >>>>> class C(types.SimpleNamespace): >> ... pass >> ... >>>>> c = C(f1=1, f2=None) >>>>> c >> C(f1=1, f2=None) >> > > Thanks for all your explanations. > This solution works. Would you please detail a little on how it works? > Or just point me out some readings. > I am confused because types.SimpleNamespace seems to be a class! It *is* a class, and by making C a subclass of SimpleNamespace C inherits the initialiser which does the actual work of updating the __dict__ of the C instance. > From docs ...: > class SimpleNamespace: > def __init__(self, **kwargs): > self.__dict__.update(kwargs) The actual implementation is written in C (the language used to implement the CPython interpreter), but following the example in the docs you can make your own SimpleNamespace... >>> class MySimpleNamespace: ... def __init__(self, **parms): self.__dict__.update(parms) ... >>> m = MySimpleNamespace(a=1, b=2) >>> m.a 1 >>> m.b 2 and when you subclass it the subclass inherits the behaviour: >>> class C(MySimpleNamespace): ... pass ... >>> c = C(x=10, y=20) >>> c.x 10 >>> c.y 20
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll 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