如何组织此代码?

时间:2014-04-09 08:20:19

标签: python class methods

我试图通过将函数转换为方法来将函数排序到适当的类中(如果合适的话,可以在类之外留下函数)。但是我不知道如何处理这个特定的功能(如下所示)。

首先,这是我的班级:

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

   def ore_blob_action(self, world, action, ticks):
      entity = self.entity
      entity_pt = entities.get_position(self.entity)
      vein = find_nearest(world, entity_pt, entities.Vein)
      (tiles, found) = blob_to_vein(world, self.entity, vein)

      next_time = ticks + entities.get_rate(entity)
      if found:
         quake = create_quake(world, tiles[0], ticks, self.image_store)
         worldmodel.add_entity(world, quake)
         next_time = ticks + entities.get_rate(entity) * 2

      schedule_action(world, self.entity,
         OreBlobAction(self.entity, self.image_store), next_time)

      return tiles

现在,这是功能:

def take_action(world, action, ticks):
   entities.remove_pending_action(action.entity, action)
   if isinstance(action, VeinAction):
      return vein_action(world, action, ticks)
   elif isinstance(action, MinerNotFullAction):
      return miner_not_full_action(world, action, ticks)
   elif isinstance(action, MinerFullAction):
      return miner_full_action(world, action, ticks)
   elif isinstance(action, OreBlobAction):
      return ore_blob_action(world, action, ticks)
   elif isinstance(action, OreTransformAction):
      return ore_transform_action(world, action, ticks)
   elif isinstance(action, EntityDeathAction):
      return entity_death_action(world, action, ticks)
   elif isinstance(action, WyvernSpawnAction):
      return wyvern_spawn_action(world, action, ticks)
   elif isinstance(action, WyvernAction):
      return wyvern_action(world, action, ticks)
   elif isinstance(action, VeinSpawnAction):
      return vein_spawn_action(world, action, ticks)
   elif isinstance(action, AnimationAction):
      return animation_action(world, action, ticks)

   return []

正如您所看到的,此函数不仅考虑了OreBlobAction类的操作,还考虑了其​​他多个操作。将此函数保留在OreBlobAction类之外会更好吗?或者有更好的方法吗?

注意:如果我将此函数从OreBlobAction类中删除,并且我尝试运行该程序,则会收到此错误:

NameError: global name 'ore_blob_action' is not defined

1 个答案:

答案 0 :(得分:1)

关于动作类型的大转换语句是重构的红旗。有什么可以阻止你移动"采取行动"方法进入动作类本身?例如

class Action(object):
    """ An action that can be performed on the game world. """

    def perform(self, world, ticks):
        """ Perform the action. """
        raise NotImplementedError()

这将是您的基本操作类,然后在每种操作类型中,您将覆盖perform(...)方法,例如

class WyvernSpawnAction(Action):
    """ An action that spawns a Wyvern. """

    [... Some action specific initialisation code here ...]

    def perform(self, world, ticks):
        """ Spawn a Wyvern. """
        world.spawn(Wyvern(...))

您的样板文件将从世界中删除,并且您现在可以自由添加新类型的操作,而不会最终在您的函数中添加数百个比较。此外,您现在可以处理操作可以继承其他操作行为的情况,而无需非常小心您的比较顺序。