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)

私はプログラミング/このウェブサイトが初めてです。提供したスクリプト情報が少なすぎる/多すぎる場合は、お知らせください。前もって感謝します!

4

3 に答える 3

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

于 2013-10-03T16:29:17.403 に答える
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)

于 2013-10-03T16:29:20.443 に答える