Python:不能在包内使用模块

时间:2012-10-09 21:38:09

标签: python import module

我在模块中有一些代码

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 个答案:

答案 0 :(得分:1)

这是它应该如何工作(不是错误,而是一个功能)。

您必须在导入中使用绝对导入包含packagename,如果您不想这样做,可以使用相关导入(即from . import inputengine)。