python NameError,但我认为名称已定义

时间:2014-01-29 01:21:45

标签: python python-2.7 import nameerror

好的,我正在浏览LPTHW并撰写游戏。我们应该将游戏划分为不同的脚本,以查看导入它们的工作原理。我有4个脚本:ex45.py执行主代码,Engine45.py是引擎,Locations45.py是位置列表,Maps45.py是保存地图值并通过位置。

运行时遇到的错误是: Traceback(最近一次调用最后一次):   文件“ex45.py”,第2行,in     导入Maps45   文件“C:\ Users \ Raistlin \ Python \ Maps45.py”,第1行,in     导入地点45   文件“C:\ Users \ Raistlin \ Python \ Locations45.py”,第4行,in     class Map(对象):   在Map中输入文件“C:\ Users \ Raistlin \ Python \ Locations45.py”,第6行     'gold_gym':Gold_gym(), NameError:名称'Gold_gym'未定义

我不明白为什么我在Locations45.py中定义Gold_gym时没有定义。

以下代码块:

ex45.py

import Engine45
import Maps45
import Locations45


a_map = Map('Gold_gym')
a_game = Engine(a_map)
a_game.run()

Engine45.py

class Engine(object):

    def __init__(self, location_map):
        print "Engine __init__ has location_map", location_map
        self.location_map = location_map

    def run(self):
        current_location = self.location_map.opening_location()
        print "Play's first scene", current_location

        while True:
            print "\n"('-' * 20)
            next_location_name = current_location.use()
            print "next location", next_location_name
            current_location = self.location_map.next_location(next_location_name)
            print "map returns new location", current_location

Locations45.py

from random import randint
from sys import exit


class Location(object):
    def use(self):
        print "This is not configured."
        exit(1)

class Loser_gym(Location):
    quips = [
        'You are worthless, goodbye.'
        'Thanks for trying noob.'
        'Sex and candy, not today.'
        ]

    def use(self):
        print Loser_gym.quips[randint(0, len(self.quips)-1)]
        exit(1)

class Gold_gym(Location):
    def use(self):
        print "Welcome to the Gold Gym. This gym will test your physical prowess."
        print "Before you there is a large pool of water with a center platform."
        print "On your person is a satchel, a whip, a hat, and a gun."
        print "Your goal is to find the way out of the gym."
        print "Acceptable inputs are satchel, whip, hat, or gun."
        print "Good Luck."

        action = raw_input("What do you do:> ")

        if action == 'satchel':
            print "You throw your satchel towards the center platform."
            print "It does absolutely nothing. Try again."
            return 'Gold_gym'

        elif action == 'whip':
            print "You use your whip somewhat akin to Indiana Jones."
            print "You swing from a pipe and land squarely on the center platform."
            print "You have survived this turmoil."
            return 'Sapphire_gym'

        elif action == 'hat':
            print "You valiantly toss your hat toward the center platform."
            print "Your hat is caught by a gust of wind and blows away."
            print "You cannot survive without your hat."
            return 'Loser_gym'

        elif action == 'gun':
            print "You shoot your about wildly in the air."
            print "A ricochet hits you in the head and you die."
            return 'Loser_gym'

        else:
            print "DOES NOT COMPUTE, TRY AGAIN."
            return 'Gold_gym'

class Sapphire_gym(Location):
    def use(self):

        print "Welcome to the Sapphire gym, here your cognitive ability will be tested."
        print "Just kidding there is no way to figure this out consistently."
        print "Before you stands a door, the door has a small keypad on it."
        print "Below the keypad is what appears to be a smart card reader."
        print "On your way to the location you picked up two smartcards off the ground."
        print "One is red and one is green."
        print "Clearly you will need to use a smartcard and guess a code(3-digits)."

        card = raw_input('Which card do you choose:> ')

        if card == 'red':
            print "A laser beam comes out of the door and cauterizes your brain."
            return 'Loser_gym'

        elif card == 'green':
            code = '%d%d%d' % (randint(0,9), randint(0,9), randint(0,9))
            guess = raw_input('What code do you enter:> ')
            guesses = 0
            while guess != code and guesses < 20 and guess != '123':
                print "INCORRECT!"
                guesses += 1
                guess = raw_input('What code do you enter:> ')

            if guess == code or guess == '123':
                print "Nice guess noob! You may press onward."
                return 'Cerulean_gym'

            else:
                print "WRONG! TOO MANY GUESSES! DIE INFERIOR BEING!"
                return 'Loser_gym'


class Cerulean_gym(Location):
    def use(self):
        print "Welcome to the final gym, the Cerulean Gym!"
        print "Before you is a 3x3 platform, your job is to cross the platform."
        print "Be warned that each tile can trigger a trap."
        print "Good luck!"

        correct_square = ['3', '1', '2']
        jump = raw_input("Square 1, 2, or 3?:> ")
        jumps = 0

        while jumps < 3:
            if jump == correct_square:
                print "Nice job! You picked the correct square!"
                jump += 1
                correct_square = correct_square[0+jump]
                jump = raw_input("Square 1, 2, or 3?:> ")
                jumps += 1

            else:
                print "YOU FAIL! Goodbye you puny infidel."
                return 'Loser_gym'
        print 'NICE JOB. YOU WIN ALL THE BASE!'

Maps45.py

import Locations45


class Map(object):
    locations = {
        'Gold_gym' : Gold_gym(),
        'Sapphire_gym' : Sapphire_gym(),
        'Cerulean_gym' : Cerulean_gym(),
        'Loser_gym' : Loser_gym()
}

    def __init__(self, start_location):
        self.start_location = start_location
        print "start_location in __init__", self.start_location

    def next_location(self, location_name):
        print "start_location in next_location"
        val = Map.locations.get(location_name)
        print "next_location returns", val
        return val

    def opening_location(self):
        return self.next_location(self.start_location)

请帮忙吗?

2 个答案:

答案 0 :(得分:2)

当你:

import Locations45

该模块是在名称空间Locations45

下导入的

所以当你打电话

Gold_gym()

它在Maps45中查找该对象,从不知道要查看Locations45

将行更改为:

locations = {
        'Gold_gym' : Locations45.Gold_gym(),
        'Sapphire_gym' : Locations45.Sapphire_gym(),
        'Cerulean_gym' : Locations45.Cerulean_gym(),
        'Loser_gym' : Locations45.Loser_gym()

答案 1 :(得分:1)

如果您只是执行import Locations45,则不会导入每个名称 - 而是将其作为一组导入。您可以使用句点引用组内的各个事物:

'Gold_gym': Locations45.Gold_gym(),
'Sapphire_gym': Locations45.Sapphire_gym(),
'Cerulean_gym': Locations45.Cerulean_gym(),
'Loser_gym': Locations45.Loser_gym()

或者,您可以专门导入所有名称:

from Locations45 import Gold_gym, Sapphire_gym, Cerulean_gym, Loser_gym

可以使这些名称无需使用前缀。