Skip to main content
 首页 » 编程设计

看似相互编辑的 Python 子类

2024年10月24日9wuhuacong

在以“Colossal Cave Adventure”、“Zork”等形式创建基本的文本冒险时,我遇到了一个问题,我的 Zombie 和 Skeleton 类似乎在相互编辑。

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 列表。