问题
My code is a bit complex so i'll show an example:
file A.py:
from B import B
class A():
def __init__(self):
self.id = 5
self.b = B()
file B.py
from A import A
class B():
def __init__(self):
self.id = 15
self.a = A()
This is the exception i get:
Traceback (most recent call last):
File "F:/Project/Code/A.py", line 1, in <module>
from B import B
File "F:\Project\Code\B.py", line 1, in <module>
from A import A
File "F:\Project\Code\A.py", line 1, in <module>
from B import B
ImportError: cannot import name B
All I want is A to contain an instance of B and B to contain an instance of A. I know that all I have to do is to convert them to a single file but I don't want to, my code is on much larger scales and my teacher force me to keep multiple short scripts instead of one long code.
Any suggestion will be appreciated.
回答1:
What you have is called an import-loop. How you go about fixing is moving the mutually dependent code to a class C
that both then reference.
In C.py
:
def class C:
def __init__(self):
# Do some stuff
# other methods
In A.py
:
from C import C
def class A(C):
def __init__(self):
# Do some stuff in A
# other methods
In B.py
:
from C import C
def class B(C):
def __init__(self):
# Do some stuff in B
# other methods
回答2:
You can not have a two-way dependency, because that would mean every b
property in A
is a B
instance that contains its own A
, and so on.
A
- id: 5
- b: B
- id: 15
- a: A
- id: 15
- b: B ...
回答3:
You are getting the error because your scripts have recursive imports.
A.py
depends from B module
. But B.py
depends from A module
. And Python can't to resolve imports.
You can write all classes in one module. Or make sure that there was no cyclic dependency.
The same problem can be with import of variables, functions.
回答4:
You can't. It's now like a loop. If you import one it imports the other.
Also, you had to add for spaces after the class A():
and class B():
.
Your code will be:
File A.py
from B import B
class A():
def __init__(self):
self.id = 5
self.b = B()
file B.py:
from A import A
class B():
def __init__(self):
self.id = 15
self.a = A()
来源:https://stackoverflow.com/questions/42012682/python-importerror-cannot-import-name