This method will be very useful since you can use objects of both classes interchangeably. This is a serious problem, I will explain that in the end.
class A: def MethodA(self): return "Inside MethodA" def __init__ (self, Friend=None): self.__dict__['a'] = "I am a" self.__dict__['Friend'] = Friend if Friend is not None: self.__dict__['Friend'].__dict__['Friend'] = self def __getattr__(self, name): if self.Friend is not None: return getattr(self.Friend, name) raise AttributeError ("Unknown Attribute `" + name + "`") def __setattr__(self, name, value): if self.Friend is not None: setattr(self.Friend, name, value) raise AttributeError ("Unknown Attribute `" + name + "`") class B: def MethodB(self): return "Inside MethodB" def __init__ (self, Friend=None): self.__dict__['b'] = "I am b" self.__dict__['Friend'] = Friend if Friend is not None: self.__dict__['Friend'].__dict__['Friend'] = self def __getattr__(self, name): if self.Friend is not None: return getattr(self.Friend, name) raise AttributeError ("Unknown Attribute `" + name + "`") def __setattr__(self, name, value): if self.Friend is not None: setattr(self.Friend, name, value) raise AttributeError ("Unknown Attribute `" + name + "`")
Explanation:
According to this page , __getattr__ and __setattr__ will be called on python objects only when the requested attribute is not found in the specific object space. Therefore, in the constructor, we establish a connection between both classes. And then when __getattr__ or __setattr__ , we reference another object using the getattr method. ( getattr , setattr ) We use __dict__ to assign values โโin the constructor so that we don't call __setattr__ or __getattr__ .
Run Examples:
b = B()
Now, a serious problem:
If we try to access an attribute that is not in both of these objects, we end up with infinite recursion. Suppose I want to access 'C' from 'a'. Since C is not in a, it calls __getattr__ and will refer to the b object. Since object b does not have C, it calls __getattr__ , which will reference object a. Thus, we find ourselves in infinite recursion. Thus, this approach works fine when you are not accessing something unknown for both objects.
thefourtheye
source share