Python 子类看似互相编辑

标签 python class subclass

在以“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/

相关文章:

python - Django,可以运行两个不同的版本吗?

C++ 从 parent 的 vector 中调用 child 的方法?

php - Symfony2 类的使用

c++ - 无法捕获子类编辑框控件的 VK_RETURN 键

python - 使用动态 base_class 在 __new__ 子类中设置属性

iphone - Objective-C @property 类对象的变量

python - 本地/全局范围

python - 使用带有 mysql 连接器 python 的上下文管理器

python - 用于分类非图像数据集的 Conv1D 显示错误 ValueError : `logits` and `labels` must have the same shape

java - 矩形面向对象开发——Equals()方法