3

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? Commented Sep 21, 2011 at 7:41

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.