2012-10-09 30 views
1

我有一些代碼模塊的Python:不能使用模塊內部封裝

import pygame 
from pygame.locals import * 

import reusable 

from state import state 

class TitleState(state.State): 
    def __init__(self): 
     #Create data batches 
     self.soundbatch = reusable.resourceloader.ResourceBatch(path="data/sound", type="ogg") 
     self.imagebatch = reusable.resourceloader.ResourceBatch(path="data/image", type="tga") 

     #Reusable stuff 
     self.inputengine = reusable.inputengine.InputEngine() 
     self.mousehandler = reusable.mousehandler.MouseHandler() 

    def update(self): 
     pygame.event.pump() 

中,但它給我的錯誤

Traceback (most recent call last): 
    File "C:\Users\Administrator\Desktop\MegaCity\Start.py", line 1, in <module> 
    import megacity.megacity 
    File "C:\Users\Administrator\Desktop\MegaCity\megacity\megacity.py", line 37, in <module> 
    themc = MegaCity() 
    File "C:\Users\Administrator\Desktop\MegaCity\megacity\megacity.py", line 25, in __init__ 
    self.titlestate = titlestate.TitleState() 
    File "C:\Users\Administrator\Desktop\MegaCity\state\titlestate.py", line 21, in __init__ 
    self.inputengine = reusable.inputengine.InputEngine() 
AttributeError: 'module' object has no attribute 'inputengine' 

然而,可重複使用的目錄中肯定有「inputengine」在它:

Directory of C:\Users\Administrator\Desktop\MegaCity\reusable 

10/09/2012 05:29 PM <DIR>   . 
10/09/2012 05:29 PM <DIR>   .. 
10/08/2012 09:34 PM    3,920 inputengine.py 
10/09/2012 04:54 PM    1,364 mousehandler.py 
10/08/2012 09:42 PM    799 resourceloader.py 
10/09/2012 05:32 PM     2 __init__.py 
10/09/2012 05:32 PM <DIR>   __pycache__ 

但是,當我做from reusable import inputengine它進口inputengine就好了。另外,在可重用的__init__.py時,我把from . import inputengine的代碼工作。對此有何洞見?

回答

1

這是它應該如何工作(不是一個錯誤,而是一個功能)。

如果您不想這樣做,您可以在發現時使用相對導入(例如from . import inputengine),您必須在導入時使用絕對導入包括包名。

+0

奇怪。看來,這不是必要的,但無論如何。我會在6分鐘內接受。 –