我试图通过将函数转换为方法将函数分类为适当的类(如果合适的话,可以将函数留在类之外)。但我不确定如何处理这个特定函数(如下所示)。你知道吗
首先,这是我的课:
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
关于动作类型的大开关语句是重构的危险信号。有什么方法可以阻止您将“take action”方法移到action类本身吗?例如
这将是您的基本操作类,然后在每种类型的操作中,您将重写
perform(...)
方法,例如从世界上删除操作的样板文件将保留下来,现在您可以自由添加新类型的操作,而无需在函数中添加更多的比较。此外,您现在可以处理这样的情况:操作可以继承其他操作的行为,而不必非常小心比较的顺序。你知道吗
相关问题 更多 >
编程相关推荐