python类依赖于eachother,如何初始化?

jgr*_*jgr 2 python

我有两节课:

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

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

我想像这样初始化他们:

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

但我不能因为'b'在做的时候不存在a = A(b).我要做:

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

但这似乎是不洁净的.这可以解决吗?

ed.*_*ed. 5

你可以让一个类实例化另一个:

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
Run Code Online (Sandbox Code Playgroud)

或者让一个班级告诉对方自己,如下:

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)
Run Code Online (Sandbox Code Playgroud)