在以“Colossal Cave Adventure”、“Zork”等形式创建基本文本冒险时,我遇到了僵尸和骷髅类似乎相互编辑的问题。
class Entity(object):
def __init__(self,name,hp,strength,defense,armor=False,weapon=Fist(),actions=["Attack","Block"]):
self.name = name
self.hp = self.maxhp = hp
self.strength = strength
self.default_defense = self.defense = defense
self.armor = armor
self.weapon = weapon
self.initiative = 0
self.actions = actions
def attack(self,target):
#An attack action
def block(self):
#A block action
def update(self):
#Updating the entity
class Zombie(Entity):
def __init__(self):
Entity.__init__(self,"Zombie",random.randint(13,20),4,5,Leather())
print self.actions #Printing the actions in order to try to fix this issue
self.actions.remove("Block")
print self.actions #Printing the actions in order to try to fix this issue
class Skeleton(Entity):
def __init__(self):
Entity.__init__(self,"Skeleton",random.randint(16,23),6,5,False,Bow(999))
print self.actions #Printing the actions in order to try to fix this issue
self.actions.remove("Block")
print self.actions #Printing the actions in order to try to fix this issue
monsters = [Zombie(),Skeleton()]
当代码运行时,它会返回
['Attack','Block']
['Attack']
['Attack']
#Error message
该错误表明 'Block'
不在骨架的 self.actions
中进行删除,但据我的理解,'Block'当调用
应该在那里。如果我在 Entity.__init__
时,monsters
中切换 Zombie()
和 Skeleton()
,问题仍然会发生,所以问题似乎是第一个子类是从两个子类中删除该条目。
我是子类的新手,所以问题很可能在于我对它们如何工作的理解有限。这是预期的行为吗?如果是这样,我如何获得我正在寻找的行为?
最佳答案
__init__
的默认参数仅计算一次。
因此,如果您不为 actions
提供其他内容,Entity
的每个实例都将引用完全相同的列表。当您从一个实例中的该列表中删除时,其他实例中的列表也会被修改。
要防止这种情况发生,请尝试以下操作:
class Entity:
def __init__(self, ... actions=None, ...):
...
if actions is None:
self.actions = ["Attack", "Block"]
else:
self.actions = actions
然后为每个实例创建actions
列表。
关于Python 子类看似互相编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35108400/