V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
limyel
V2EX  ›  Python

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

  •  
  •   limyel · 2019-08-06 21:19:55 +08:00 · 1280 次点击
    这是一个创建于 1696 天前的主题,其中的信息可能已经有所发展或是发生改变。

    做毕设时遇到一个问题,就是假设现在有 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'

    请问有什么解决办法吗。

    no1xsyzy
        1
    no1xsyzy  
       2019-08-06 21:42:42 +08:00
    循环引用?泄漏预定
    zhze93
        2
    zhze93  
       2019-08-06 21:44:07 +08:00
    A,B 互相调用,你想调用对方的什么。
    Takamine
        3
    Takamine  
       2019-08-06 22:33:21 +08:00
    为什么我感觉你这是想要多继承呢。
    limyel
        4
    limyel  
    OP
       2019-08-06 22:36:46 +08:00
    @Takamine 😂已经解决了
    limyel
        5
    limyel  
    OP
       2019-08-06 22:37:31 +08:00
    @zhze93 一个是 UI 模块,一个是网络链接模块,好在刚刚解决了😄
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2998 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 14:44 · PVG 22:44 · LAX 07:44 · JFK 10:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.