this is probably a simple problem so hopefuly its easy for someone to point out my mistake or if this is even possible.
I have an object that has multiple objects as properties. I want to be able to dynamically set the properties of these objects like so:
class Person(object):
def __init__(self):
self.pet = Pet()
self.residence = Residence()
class Pet(object):
def __init__(self,name='Fido',species='Dog'):
self.name = name
self.species = species
class Residence(object):
def __init__(self,type='House',sqft=None):
self.type = type
self.sqft=sqft
if __name__=='__main__':
p=Person()
setattr(p,'pet.name','Sparky')
setattr(p,'residence.type','Apartment')
print p.__dict__
The output is:
{'pet': <main.Pet object at 0x10c5ec050>, 'residence': <main.Residence object at 0x10c5ec0d0>, 'pet.name': 'Sparky', 'residence.type': 'Apartment'}
As you can see, rather then having the name attribute set on the pet object of the person, a new attribute "pet.name" is created.
I cannot specify person.pet to setattr because different child-objects will be set by the same method, which is parsing some text and filling in the object attributes if/when a relevant key is found.
Is there a easy/built in way to accomplish this?
Or perhaps I need to write a recursive function to parse the string and call getattr multiple times until the necessary child-object is found and then call setattr on that found object?
Thank you!