python classes dependant on eachother, how to init?
我有两个班:
1 2 3 4 5 6 7 | class A(object): def __init__(self, b): self b = b class B(object): def __init__(self, a): self a = a |
我想这样初始化它们:
1 2 | a = A(b) b = B(a) |
但我做不到,因为在做
1 2 3 | a = A() b = B(a) b.a = a |
但这似乎不干净。这是可以解决的吗?
您可以让一个类实例化另一个类:
1 2 3 4 5 6 7 8 9 10 | 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 |
或者让一个类告诉另一个类关于它自己,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 | 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) |