为什么我得到这个NameError?

时间:2014-04-09 22:52:28

标签: python class methods

这是错误:

 File "/Users/KarenLee/Desktop/temp/worldmodel.py", line 76, in update_on_time
    obj = VeinAction(entity, image_store)
NameError: global name 'VeinAction' is not defined

这是我的代码(这是在“actions.py”文件中):

import entities
import worldmodel
import pygame
import math
import random
import point
import image_store

BLOB_RATE_SCALE = 4
BLOB_ANIMATION_RATE_SCALE = 50
BLOB_ANIMATION_MIN = 1
BLOB_ANIMATION_MAX = 3

FREEZE_ANIMATION_RATE = 100
FREEZE_STEPS = 4

ORE_CORRUPT_MIN = 20000
ORE_CORRUPT_MAX = 30000

QUAKE_STEPS = 10
QUAKE_DURATION = 1100
QUAKE_ANIMATION_RATE = 100

VEIN_SPAWN_DELAY = 500
VEIN_RATE_MIN = 8000
VEIN_RATE_MAX = 17000

WYVERN_RATE_MIN = 200
WYVERN_RATE_MAX = 600
WYVERN_ANIMATION_RATE = 100

class VeinAction:
   def __init__(self, entity, image_store):
      self.entity = entity
      self.image_store = image_store

   def vein_action(self, world, action, ticks):
      entity = self.entity
      open_pt = find_open_around(world, entities.get_position(entity),
         entities.get_resource_distance(entity))
      if open_pt:
         ore = create_ore(world,
            "ore - " + entities.get_name(entity) + " - " + str(ticks),
            open_pt, ticks, action.image_store)
         worldmodel.add_entity(world, ore)
         tiles = [open_pt]
      else:
         tiles = []

      schedule_action(world, entity, VeinAction(entity, action.image_store),
         ticks + entities.get_rate(entity))
      return tiles

   def vein_take_action(self, world, action, ticks):
      entities.remove_pending_action(self.entity, action)
      if isinstance(action, VeinAction):
         return self.vein_action(world, action, ticks)

这是在“worldmodel.py”文件中:

import entities
import pygame
import ordered_list
import actions
import occ_grid
import point

class WorldModel:
   def __init__(self, num_rows, num_cols, background):
      self.background = occ_grid.Grid(num_cols, num_rows, background)
      self.num_rows = num_rows
      self.num_cols = num_cols
      self.occupancy = occ_grid.Grid(num_cols, num_rows, None)
      self.entities = []
      self.action_queue = ordered_list.OrderedList()

def update_on_time(world, ticks):
   tiles = []

   next = world.action_queue.head()
   obj = VeinAction(entity, image_store)
   while next and next.ord < ticks:
      world.action_queue.pop()
      tiles.extend(obj.vein_take_action(world, next.item, ticks))
      tiles.extend(actions.take_action(world, next.item, ticks))
      next = world.action_queue.head()

   return tiles

错误消息来自“worldmodel.py”中的update_on_time函数。我认为这就是你如何从函数中的不同文件中的类调用方法,但它不起作用!这样做的正确方法是什么?或者,是否可以这样做?提前谢谢。

1 个答案:

答案 0 :(得分:4)

您导入了包含actions的模块VeinAction。但是,Python并不知道这一点。您需要通过在其前面添加VeinAction告诉Python actions.所在的位置:

obj = actions.VeinAction(entity, image_store)

那,或者您可以直接导入VeinAction

from actions import VeinAction

无论哪种方式,您都需要确保Python可以找到类VeinAction