extended setattr()

R

Rotlaus

2 weeks ago i asked for a etended getattr() which worked really fine,
but now i would love to have a extended setattr() as well.

Lets assume i have some classes:

class A(object):
def __init__(self):
self.B = B()

class B(object):
def __init__(self):
self.C = C()

class C(object):
def __init__(self, foo='', bar=''):
self.foo = foo
self.bar = bar

and now i wanna do something like this:

a=A()
ext_setattr(a, 'B.C', ('a', 'b'))

Is this possible? It would also be nice if the attributes would be
created if they not exist, always implying that
objectname==objecttype.

Kind regards,

Andre
 
R

Rotlaus

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
Traceback (most recent call last):
'foo'

What am i doing wrong?
 
D

Diez B. Roggisch

Rotlaus said:
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

Traceback (most recent call last):

'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
 
A

Andre Adrian

Diez B. Roggisch said:
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)
 
D

Diez B. Roggisch

Andre said:
Why is this so? Shouldn't it be the same?

No, of course not!

obj = val

binds the object reffered to by val to the LOCAL name obj. That's python
101, make sure you get variables/names and scopes proper.
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)

Yep.

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top