[英]Python How Can I make base class file can import from child class file
我遇到了python导入循环问题。 而且我不想将两段代码合并到一个文件中。 我能做什么?
$ tree
.
├── testBase.py
└── testChild.py
testBase.py:
from testChild import Child
class Base(object):
def __init__(self, obj):
## For some rease need detect obj
if isinstance(obj, Child):
print("test")
testChild.py:
from testBase import Base
class Child(Base):
def __init__(self):
pass
有错误:
$ python testChild.py
Traceback (most recent call last):
File "testChild.py", line 1, in <module>
from testBase import Base
File "/cygdrive/d/Home/test_import/testBase.py", line 2, in <module>
from testChild import Child
File "/cygdrive/d/Home/test_import/testChild.py", line 1, in <module>
from testBase import Base
ImportError: cannot import name Base
我可以像这样在运行时进行导入:
class Base(object):
def __init__(self, obj):
from testChild import Child
## For some rease need detect obj
if isinstance(obj, Child):
print("test")
我想知道这是解决此问题的唯一方法吗? 有没有好的方法?
您可以通过在导入中避免使用from
来避免收到错误消息:
testBase.py:
import testChild
class Base(object):
def __init__(self, obj):
## For some rease need detect obj
if isinstance(obj, testChild.Child):
print("test")
testChild.py:
import testBase
class Child(testBase.Base):
def __init__(self):
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.