extended setattr()

Rotlaus rotlaus at gmail.com
Tue Jul 8 08:27:06 CEST 2008


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?



More information about the Python-list mailing list