2013-10-03 60 views
0

我目前在学习python的开始。我使用课堂做了一个游戏。但现在我需要将这些类放在另一个文件中,并从主文件中导入它们。现在我有:导入模块并创建它的一个实例

a_map = Map("scene_1") 
game = Engine(a_map) 
game.play() 

我似乎无法使用模块制作一个像这样的实例。我想:

a_map = __import__('map') 
game = Engine(a_map) 
game.play() 

但是,这给我的错误

AttributeError: 'module' object has no attribute 'first_scene' 

这是怎么回事错在这里?这是发动机/地图类:

class Engine(object): 

def __init__(self, map): 
    self.map = map 

def play(self): 
    current_scene = self.map.first_scene() 
    while True: 
     next = current_scene.enter() #call return value of the current scene to 'next' 
     current_scene = self.map.next_scene(next) #defines the subsequent scene 

class Map(object): 

scenes = {"scene_1" : Scene1(), 
      "scene_2" : Scene2(), 
      "scene_3" : Scene3() 
     } 

def __init__(self, start_scene): 
    self.start_scene = start_scene 

#defines the first scene, using the 'scenes' array. 
def first_scene(self): 
    return Map.scenes.get(self.start_scene) 

#defines the second scene, using the 'scenes' array.  
def next_scene(self, next_scene): 
    return Map.scenes.get(next_scene) 

我是新来的编程/这个网站。如果我提供的信息太少/太多,请告诉我。提前致谢!

回答

1

您似乎将引擎的map成员设置为map模块,而不是Map对象的实例。如果您MapEngine类是在map.py定义,那么你就可以从主文件中像这样创建实例:

from map import Map, Engine 
a_map = Map("scene_1") 
game = Engine(a_map) 
game.play() 
1

在每个模块开始,你应该列出要导入的功能/班/模块。

如果包含您的类文件在同一目录作为您的主要文件,太好了,你可以这样做(假设包含您的类文件被称为foo.py和bar.py):

from foo import Map 
from bar import Engine 

再后来就在你的主文件

a_map_instance = Map('scene_1') 
an_engine_instance = Engine(a_map_instance) 
an_engine_instance.play() 

如果你有其他地方存储的文件,那么你需要的位置添加到你的Python路径。请参阅此处的文档以了解如何识别sys.path中的位置()

http://docs.python.org/2/tutorial/modules.html#the-module-search-path

+0

感谢您的答案家伙!当我尝试: 'from map import' 有一个错误: 'ImportError:无法导入名称映射'。 当我尝试只是'导入地图'它给了我这个错误: AttributeError:'模块'对象没有属性'地图''。 这些文件都在同一个目录中... – Felix

+0

Felix - 包含Map类的文件的名称是什么?它绝对是map.py? python解释器将查找与正在运行的脚本相同的目录,以查找具有指定名称的模块。 – melipone

+0

我有3个文件:'ex45files.py'(主文件),'map.py'(包含地图类)和'engine.py'(包含引擎类)。我把这三个放在完全相同的目录中,但是它给了我错误:AttributeError:'module'对象没有属性'Map'。使用代码: 'a_map = map.Map('scene_1') game = engine.Engine(a_map) game.play()' 什么对我来说也是新的,当我运行主文件(ex45文件。 py),它为所有3个文件创建'.pyc'文件... – Felix

0

假设你的Map类在map.py中,而你的Engine类在engine.py中,你只需要将它们导入到你的文件中。使用其中定义的内容时,还需要引用该模块。例如:

import map 
import engine 

a_map = map.Map('scene_1') 
game = engine.Engine(a_map) 
game.play() 

您也可以导入特定项目从模块,from map import Map将允许你这样做a_map = Map('scene_1)

相关问题