2014-09-04 27 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