ImportError: Cannot import name X

前端 未结 16 1225
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 04:33

I have four different files named: main, vector, entity and physics. I will not post all the code, just the imports, because I think that\'s where the error is. (If you want

16条回答
  •  自闭症患者
    2020-11-22 04:47

    The problem is clear: circular dependency between names in entity and physics modules.

    Regardless of importing the whole module or just a class, the names must be loaded .

    Watch this example:

    # a.py
    import b
    def foo():
      pass
    b.bar()
    
    # b.py
    import a
    def bar():
      pass
    a.foo()
    

    This will be compiled into:

    # a.py
    # import b
    # b.py
    # import a # ignored, already importing
    def bar():
      pass
    a.foo()
    # name a.foo is not defined!!!
    # import b done!
    def foo():
      pass
    b.bar()
    # done!
    

    With one slight change we can solve this:

    # a.py
    def foo():
      pass
    import b
    b.bar()
    
    # b.py
    def bar():
      pass
    import a
    a.foo()
    

    This will be compiled into:

    # a.py
    def foo():
      pass
    # import b
    # b.py
    def bar():
      pass
    # import a # ignored, already importing
    a.foo()
    # import b done!
    b.bar()
    # done!
    

提交回复
热议问题