所以我之前发布了这个,但我没有遵循社区准则,所以我决定这次按照社区准则再次发布。 (我试图删除我的其他问题,但它不会让我)
以下是我可以用来创建同样问题的最少量代码:
class Object:
def __init__(self, *args, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
self.inventory = []
try: self.itemComponent.owner = self
except: self.itemComponent = None
class Item:
def drop(self):
for obj in objects:
if self.owner in obj.inventory:
objects.append(self.owner)
obj.inventory.remove(self.owner)
def monster_death(monster):
monster.name = 'Goblin Corpse'
for element in monster.inventory:
if element.itemComponent:
element.itemComponent.drop()
objects = []
#Create Goblin
monster = Object(name = 'Goblin')
#Populate Goblin's Equipment
monster.inventory = [
Object(name='Dagger', itemComponent=Item() ),
Object(name='Light Healing Potion', itemComponent=Item() ),
Object(name='Scroll of Chain Lightning', itemComponent=Item())
]
objects.append(monster)
print '=~In Monster Inventory~='
for item in monster.inventory:
print item.name
print
print '=~In World~='
for obj in objects:
print obj.name
print
print '***MONSTER DIES***'
print
monster_death(monster)
print '=~In Monster Inventory~='
print
for item in monster.inventory:
print item.name
print
print '=~In World~='
print
for obj in objects:
print obj.name
其中一个项目总是停留在怪物库存中...似乎几乎随机的是哪个项目保留,但每次都是相同的项目,除非我删除或添加更多项目到他的库存。
答案 0 :(得分:1)
您正在从当前正在迭代的列表中删除,这将影响迭代。
如果您需要处理每个项目,请在循环中执行此操作,然后清除列表
my_list = ['a', 'b', 'c']
my_list[:] = [] # clear the list without replacing it