1

我在模块中有一些代码

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'

但是,reusable 目录中肯定有“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代码工作。对此有任何见解吗?

4

1 回答 1

1

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

你必须在你的导入中包含包名和绝对导入,如果你不想这样做,你可以使用你发现的相对导入(即from . import inputengine)。

于 2012-10-09T21:41:52.010 回答