Passing new fields to an object
Peter Otten
__peter__ at web.de
Fri Jun 12 15:12:26 EDT 2015
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
More information about the Python-list
mailing list