Having the code:
class values:
class struct1:
def __init__(self):
self.a = 1
self.b = 2
class struct2:
def __init__(self):
self.c = 3
self.d = 4
def __init__(self):
self.struct1 = self.struct1()
self.struct2 = self.struct2()
def setValue(self, **kwargs):
for key, value in kwargs.items():
try:
getattr(self.struct1, key)
except AttributeError:
# self.struct1 don't have any attribute which name is the value of 'key'.
pass
else:
setattr(self.struct1, key, value)
try:
getattr(self.struct2, key)
except AttributeError:
# self.struct2 don't have any attribute which name is the value of 'key'.
pass
else:
setattr(self.struct2, key, value)
You can:
>>> st = values()
>>> st.struct1.a = 10
>>> st.struct2.c = 20
>>> print(st.struct1.a)
>>> 10
>>> print(st.struct2.c)
>>> 20
>>> st.setValue(b=20, a=100, d=50, c=60)
>>> print(st.struct1.a)
>>> print(st.struct1.b)
>>> print(st.struct2.c)
>>> print(st.struct2.d)
>>> 100
>>> 20
>>> 60
>>> 50
EDIT: In your original question you had __init
instead __init__
and:
self.struct1 = self.struct1()
self.struct1 = self.struct2() # Here you was redefining self.struct1
I changed to:
self.struct1 = self.struct1()
self.struct2 = self.struct2()