3
votes

I have two classes:

class A(object):
  def __init__(self, b):
    self b = b

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

I'd like to init them like this:

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

But I can't since 'b' doesn't exist when doing a = A(b). I have to do:

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

But that seems unclean. Is this solvable?

1
Do you really need to assign the references during initialization? How about assigning them after creating the instances?Jeff Mercado

1 Answers

6
votes

You could either make one class instantiate the other:

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

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

a = A()
b = a.b

Or make one class tell the other about itself, like this:

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

class B(object):
  def __init__(self):
    #Will be set by A later
    self.a = None

b = B()
a = A(b)