试图让班级定义敌人

时间:2018-09-28 13:24:36

标签: python class

我真的不知道该怎么说,除了:这项工作有效吗,我可以像布什声明那样在其中添加更多内容吗?

class Enemy():

def __init__(self, name, HP, skills, attack, defense, loot, expget, flvrtxt):
    self.name = name
    self.HP = health
    self.skills = skills
    self.attack = attack
    self.defense = defense
    self.loot = loot
    self.expget = expget
    self.flvrtxt = text

bush = Enemy()
bush.name = "Bush"
bush.HP = 10
bush.skills = "none"
bush.attack = 0
bush.defense = 5
bush.loot = "A stick"
bush.expget = 50
bush.flvrtxt = "Just a bush, it cannot attack"

通过添加更多内容,我的意思是我基​​本上可以复制并粘贴灌木丛定义,更改统计信息并结成新敌人吗? 例如,我可以添加这个吗?:

imp = Enemy():
imp.name = "Imp"
imp.HP = 50
imp.skills = "none"
imp.attack = 10
imp.defense = 10
imp.loot = "gold"
imp.expget = 150
imp.flvrtxt = "Cliche RPG enemy"

1 个答案:

答案 0 :(得分:1)

在我的脑海中,我可以想到两种方法,具体取决于您要实现的目标。

现在,通过代码的结构化方式,可以创建Enemy类的实例,该实例由其参数定义。正如@Patrick Haugh在评论部分中指出的那样,如果将方法更新为标题为Enemy的方法,则可以在构造时显式设置__init__(self, name, HP, skills, attack, defense, loot, expget, flvrtxt)的所有属性:

class Enemy(object):

    def __init__(self, name, HP, skills, attack, defense, loot, expget, flvrtxt):
        self.name = name
        self.HP = HP
        self.skills = skills
        self.attack = attack
        self.defense = defense
        self.loot = loot
        self.expget = expget
        self.flvrtxt = flvrtext


bush = Enemy("Bush", 10, "none", 0, 5, "A Stick", 50, "Just a bush, it cannot attack")
imp = Enemy("Imp", 50, "none", 10, 10, "gold", 150, "Cliche RPG enemy")

或者,如果您要实例化BushImp的特定类型,则可能希望将它们创建为自己的类,以它们作为Enemy类的子类。自己的关联字段的默认实现:

class Bush(Enemy):

    def __init__(self):
        super(Bush, self).__init__("Bush", 10, "none", 0, 5, "A Stick", 50, "Just a bush, it cannot attack")

class Imp(Enemy):

    def __init__(self):
        super(Imp, self).__init__("Imp", 50, "none", 10, 10, "gold", 150, "Cliche RPG enemy")

通过这种方式,您可以编写类似以下的代码,以实例化一个Bush,该{-{1}}会预先填充您在其类中为Bush定义的所有字段:

bush = Bush();