extended setattr()
Andre Adrian
rotlaus at gmail.com
Tue Jul 8 06:59:32 EDT 2008
Diez B. Roggisch <deets <at> nospam.web.de> writes:
> > 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.
Why is this so? Shouldn't it be the same?
> You need to use a setattr(obj, name, val)
> on the last attribute-name.
Ok, so this works:
def ext_setattr(obj, attr, val):
attributes = attr.split('.')
for subattr in attributes[:-1]:
obj = getattr(obj, subattr)
setattr(obj, attributes[-1], val)
More information about the Python-list
mailing list