Suppose I have two Python classes, A and B. I would like to be able to do the following:
>>> b = B()
>>> b.a.attr1 = 'foo'
>>> b.a.attr2 = 'bar'
where ‘a’ is an instance of A. I can’t use __setattr__ as I would if ‘a’ was some
“primitive” type. Is there some elegant way to accomplish this, other than
>>> b = B()
>>> b.a = A()
>>> b.a.attr1 = 'foo'
>>> b.a.attr2 = 'bar'
?
You’d have to either create
ain the__init__ofB, use a__getattr__hook to createadynamically, or use a property.__init__approach:__getattr__approach:Property approach:
Of course, the property and
__getattr__approaches do not have to store theA()instance onself, it could just return a pre-existingA()instance from somewhere else instead.