2014-04-18 46 views
2

我有下面的代碼(簡稱爲清楚起見):Python的繼承 - 名未被定義

face.py:

from frame import * 

class Face(Frame): 
    def hello(self): 
     print 'hello' 

frame.py:

from face import * 

class Frame(object): 
    def __init__(self, image): 
    self.image = image 

我會出現以下錯誤:

Traceback (most recent call last): 
    File "2.py", line 2, in <module> 
    from frame import * 
    File "/home/code/iris/frame.py", line 4, in <module> 
    from face import * 
    File "/home/code/iris/face.py", line 7, in <module> 
    class Face(frame.Frame): 
NameError: name 'frame' is not defined 

whic^h我覺得是我要麼辦法做到:

  • 設置我的「進口」
  • 設置我的班

任何想法我做了什麼錯?此外,如果任何人都可以解釋哪裏「進口」是必要的,這將是有益的!

謝謝! Chris。

+3

你爲什麼從幀導入的臉?你有一個循環導入。 –

+0

我的一個框架功能將創建一個新的臉 - 所以我想我想要它加載,對吧? – cjm2671

+2

似乎你需要重新設計你的課程。循環依賴不是一個好主意。 –

回答

3

您正在進入循環依賴的陷阱。你的臉部類取決於框架類,而你的框架類取決於臉部類,從而形成像情況一樣的循環死鎖。以從Handle circular dependencies in Python modules?

有解決這個問題的方式在Python參考: The good option: Refactor your code not to use circular imports. The bad option: Move one of your import statements to a different scope.

+0

解決方案是爲Frame&Face創建一個超級類,Frame&Face是並排的,並且都可以繼承超類的常用函數? – cjm2671

+0

@ cjm2671是的,這是一個更好的解決方案 –

+0

一個簡單得多的解決方法可能是放棄'from module import *'語法並只導入模塊本身(並且稍後使用'module.obj'而不是'obj')。如果您只有頂級的類和函數定義,通常您可以通過循環導入獲得。 – Blckknght