Passing new fields to an object

Paulo da Silva p_s_d_a_s_i_l_v_a_ns at netcabo.pt
Fri Jun 12 23:33:29 EDT 2015


On 13-06-2015 02:25, Steven D'Aprano wrote:
> On Fri, 12 Jun 2015 16:53:08 +0100, Paulo da Silva wrote:
> 
...

> 
> You should use SimpleNamespace, as Peter suggests, but *not* subclass it. 
> If you subclass it and add methods:
> 
> class C(SimpleNamespace):
>     def foo(self, arg):
>         print("called foo")
> 
> 
> then you risk overriding foo method, as above. If you don't add methods, 
> there is no need to subclass.
> 
> Instead, use composition: your class should *contain* a SimpleNamespace, 
> not *be* one:
> 
> class C:
>     def __init__(self, **param):
>         self.ns = SimpleNamespace(param)
>     def __getattr__(self, attrname):
>         return getattr(self.ns, attrname)
>     def foo(self, arg):
>         print("called foo")
> 
> 
> instance = C(a=1, b=2, foo=3)
> # later
> instance.foo("x")  # prints "called foo"
> 
> 
> The special method __getattr__ only runs if the attribute name is not 
> found in the usual way, so the method foo will continue to be found and 
> not be overridden by the param foo.

Always learning!

Thanks a lot.





More information about the Python-list mailing list