Consider that we have 5 python classes X1, X2, X3, X4, X5 and the following code:
class Schedule:
def __init__(self):
pass
class DateBound:
def __init__(self):
self.attr3 = Schedule()
class Behavior:
def __init__(self):
self.attr2 = DateBound()
class Host:
def __init__(self):
self.attr1 = Behavior()
class PeriodController:
def __init__(self):
self.attr0 = Host()
Now suppose a function in PeriodController needs to access attr3 of class DateBound :
class PeriodController:
def __init__(self):
self.attr0 = ()
def example_function(self):
return self.attr0.attr1.attr2.attr3
How would I efficiently access attr3 in such a situation ? I have nothing against accessing it like the example_function(), but it does not seem right because of the repetition of attr0.attr1 ... attrn
Briefly, the conception of this implementation is that a Host has a Bahavior that defines among others at which time he should be connected to the server.
The DateBound class exists, because sometimes a Host can be connected to the server at a different time from its normal Behavior time, but it is indeed the good Host, hence none regular connection times of the Host are specified using a Datebound instance.
A DateBound has a Schedule which contains the times which a DateBound instance has, hence the times the Host should be connected. Finally the PeriodController, controls if the Host is connected according to its normal Behavior, thus PeriodController needs to access self.attr3
You can use recursion:
class X5:
def __init__(self):
self.attr0 = X4()
def example_function(self, count = 1):
if count == 4:
return self.attr0
self.attr0 = getattr(self.attr0, f'attr{count}')
return self.example_function(count+1)
print(X5().example_function())
Output:
<__main__.X1 object at 0x1012cc278>
Printing X5().attr0.attr1.attr2.attr3)
achieves the same result:
<__main__.X1 object at 0x1012cc278>
Adding __repr__
methods to each class makes for easier visualization:
class X1:
...
def __repr__(self):
return f'<{self.__class__.__name__}>'
print(X5().example_function())
Output:
<X1>