extended setattr()

Diez B. Roggisch deets at nospam.web.de
Tue Jul 8 02:29:14 EDT 2008


Rotlaus schrieb:
> On 7 Jul., 08:01, Rotlaus <rotl... at gmail.com> wrote:
>> 2 weeks ago i asked for a etended getattr() which worked really fine,
>> but now i would love to have a extendedsetattr() as well.
> 
> I've tried the following, but it doesn't work:
> 
> class A(object):
>     def __init__(self):
>         self.B = B()
> 
> class B(object):
>     def __init__(self):
>         self.C = C('foo')
> 
> class C(object):
>     def __init__(self, txt=''):
>         self.txt = txt
> 
> def ext_setattr(obj, attr, val):
>     for subattr in attr.split("."):
>         obj = getattr(obj, subattr)
>     obj = val
> 
>>>> import test
>>>> a = A()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'A' is not defined
>>>> a = test.A()
>>>> a.B.C.txt
> 'foo'
>>>> ext_setattr(a, 'B.C.txt', 'bar')
>>>> a.B.C.txt
> 'foo'
> 
> What am i doing wrong?

obj = val won't work.

You need to use a setattr(obj, name, val)

on the last attribute-name.

Diez



More information about the Python-list mailing list