2014-09-04 33 views
0

我遇到了python导入循环问题。我不想将两部分代码合并到一个文件中。我能做什么?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") 

我想知道这是解决此问题的唯一方法吗?有一个好方法吗?

+3

这就是最正常的方式来做到这一点。 。 。但是,一般来说,基类不应该知道它的子类。强迫基地知道孩子是有点代码味道。 – mgilson 2014-09-04 17:54:47

+1

目前还不清楚你想要实现什么 - 你有两个文件试图从彼此导入,一个父类(也是?)紧密地耦合到它的孩子,并没有说他们为什么不能在一个文件中。 – jonrsharpe 2014-09-04 17:55:11

+0

听起来像是将你的孩子方法重载给我的工作。 – 2014-09-04 17:56:12

回答

1

您可以避免你被避免你的进口使用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 
+2

但是,对于你的问题的评论是正确的:在你解决你的设计问题之后,这个编码问题就会消失。 – 2014-09-04 20:36:32