Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python classes dependant on eachother, how to init?

Tags:

python

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?

like image 929
jgr Avatar asked Jan 18 '26 14:01

jgr


1 Answers

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)
like image 62
ed. Avatar answered Jan 21 '26 04:01

ed.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!