推荐学习书目
› 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 · Aug 6, 2019 · 2351 views
    This topic created in 2606 days ago, the information mentioned may be changed or developed.

    做毕设时遇到一个问题,就是假设现在有 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.b 在 self.a 之后,所以上面的代码就会报错 AttributeError: 'C' object has no attribute 'b'。

    请问有什么解决办法吗。

    no1xsyzy
        1
    no1xsyzy  
       Aug 6, 2019
    循环引用?泄漏预定
    zhze93
        2
    zhze93  
       Aug 6, 2019
    A,B 互相调用,你想调用对方的什么。
    Takamine
        3
    Takamine  
       Aug 6, 2019
    为什么我感觉你这是想要多继承呢。
    limyel
        4
    limyel  
    OP
       Aug 6, 2019
    @Takamine 😂已经解决了
    limyel
        5
    limyel  
    OP
       Aug 6, 2019
    @zhze93 一个是 UI 模块,一个是网络链接模块,好在刚刚解决了😄
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2579 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 02:07 · PVG 10:07 · LAX 19:07 · JFK 22:07
    ♥ Do have faith in what you're doing.