I have a piece of code where I have an object B that has another object A as a property, and I would like the user to be able to set the properties of either object by name. How can I let the user set attributes of either A or B?
The following code illustrates what I am trying to do:
>>> class A:
... def __init__(self):
... self.asd = 123
>>> class B:
... def __init__(self, a):
... self.a = a
>>> a=A()
>>> b=B(a)
>>> b.a.asd
123
>>> setattr(b, 'a.asd', 1000)
>>> b.a.asd
123 # I would like this to be 1000
I would like to only prompt the user for the property name and value.
I am prompting the user with this code:
prop = input("Property name to set: ")
try:
print(f"Current value of property {prop}: {getattr(B, prop)}")
value = input("Property value to set: ")
setattr(B, prop, value)
except AttributeError:
print(f"Object {B} has no property named {prop}. See {dir(B)}")
Edit: question solved, but I cannot accept my own answer for 2 days
setattr(b.a, 'asd', 1000)?b.athough. I want the user to be able to set properties of both A and B. Updated the question for clarity.