Python 中 __init__ 实例变量定义顺序的问题

2019-08-06 21:19:55 +08:00
 limyel

做毕设时遇到一个问题,就是假设现在有 A、B 两个不同的类,需要相互调用,于是我就写了一个 C 类来沟通两者,如下面的代码所示:

class A:
    def __init__(self, value, main):
        self.main = main
        self.value = value
        self.output()

    def output(self):
        print(self.main.b.value)


class B:
    def __init__(self, value, main):
        self.main = main
        self.value = value
        self.output()
	
    def output(self):
    	print(self.main.a.value)
    

class C:
    def __init__(self):
        self.a = A(1, self)
        self.b = B(2, self)


c = C()

但是这样就有个问题,因为 self.bself.a 之后,所以上面的代码就会报错 AttributeError: 'C' object has no attribute 'b'

请问有什么解决办法吗。

1314 次点击
所在节点    Python
5 条回复
no1xsyzy
2019-08-06 21:42:42 +08:00
循环引用?泄漏预定
zhze93
2019-08-06 21:44:07 +08:00
A,B 互相调用,你想调用对方的什么。
Takamine
2019-08-06 22:33:21 +08:00
为什么我感觉你这是想要多继承呢。
limyel
2019-08-06 22:36:46 +08:00
@Takamine 😂已经解决了
limyel
2019-08-06 22:37:31 +08:00
@zhze93 一个是 UI 模块,一个是网络链接模块,好在刚刚解决了😄

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/589628

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX