Skip to content Skip to sidebar Skip to footer

How To Instantiate Classes That Depend On Each Other?

I have a PlayoffCreator class to create playoff matches. This class has a Bracket instance which generates the structure of the bracket, and each match in this structure is a Node,

Solution 1:

I see two possibilities.

1 - Instantiate the two elements, then setup the dependency

class A:
    def __init__(self):
        self.b = None

class B:
    def __init__(self):
        self.a = None

a = A()
b = B()
a.b = b
b.a = a

You can push this further by adding a b optional parameter in A's constructor, that defaults to None, and doing the same for B:

class A:
    def __init__(self, b=None):
        self.b = b

class B:
    def __init__(self, a=None):
        self.a = a

This allows you to instantiate the second by passing the first's instance:

a = A()
b = B(a)
a.b = b

2 - Instantiate B at A instantiation, then get that instance

class A:
    def __init__(self):
        self.b = B(self)

class B:
    def __init__(self, a):
        self.a = a

a = A()
b = a.b

Both method have their advantages and drawbacks. I would prefer n°1, for it's more flexible, because symmetrical. However, if there is a logical hierarchy between the two classes, n°2 might be used as well.


Post a Comment for "How To Instantiate Classes That Depend On Each Other?"