Let's say I have two classes A and B:
Class A:
# A's attributes and methods here
Class B:
# B's attributes and methods here
Now I can assess A's properties in object of B class as follows:
a_obj = A()
b_obj = B(a_obj)
What I need is a two way access. How do I access A's properties in B and B's properties in A ?
You need to create pointers either way:
Now
A
can refer toself.parent
(provided it is notNone
), andB
can refer toself.child
. If you try to make an instance ofA
the child of more than oneB
, the last 'parent' wins.Why not just plan your objects in a way where this can be taken care of with inheritance.
In this case by planing ahead, you could just use
C
for a generalist object, andA
withB
as more specialised/bare parents.This method will be very useful, as you can use objects of both the classes interchangeably. There is a serious problem with this, I ll explain that at the end.
Explanation:
As per this page,
__getattr__
and__setattr__
will be invoked on python objects only when the requested attribute is not found in the particular object's space. So in the constructor we are establishing relationship between both the classes. And then whenever__getattr__
or__setattr__
is called, we refer the other object usinggetattr
method. (getattr, setattr) We use__dict__
to assign values in the constructor, so that we ll not call__setattr__
or__getattr__
.Sample Runs:
Now, the serious problem:
If we try to access an attribute which is not there in both these objects, we ll end up in infinite recursion. Lets say I want to access 'C' from 'a'. Since C is not in a, it will call
__getattr__
and it will refer b object. As b object doesnt have C, it will call__getattr__
which will refer object a. So we end up in an infinite recursion. So this approach works fine, when you you don't access anything unknown to both the objects.