首页 > 解决方案 > 我正在尝试优化一些类,但代码不起作用

问题描述

#Here is the code I currently have:
class Character(object):
    def __init__(self, currentHealth, maxHealth, damage, defence, agility):
        self.currentHealth = currentHealth
        self.maxHealth = maxHealth
        self.damage = damage
        self.defence = defence
        self.agility = agility

class Enemy(Character):
    def __init__(self, drop):
        Character.__init__(self, currentHealth, maxHealth, damage, defence, agility)
        self.drop = drop

    def checkHealth(self):
        print("The enemies health is: " + str(self.currentHealth))

    def inspectStats(self):
        print("The enemies health is: " + str(self.currentHealth))
        print("The enemies attack is: " + str(self.damage))
        print("The enemies defence is: " + str(self.defence))
        print("The enemies evasiveness is: " + str(self.agility))

class Player(Character):
    def __init__(self, currentHealth, maxHealth, damage, defence, agility, gold):
        self.currentHealth = currentHealth
        self.maxHealth = maxHealth
        self.damage = damage
        self.defence = defence
        self.agility = agility
        self.gold = gold

    def checkHealth(self):
        print("Your current health is: " + str(self.currentHealth))

    def inspectStats(self):
        print("Your current health is: " + str(self.currentHealth))
        print("Your max health is: " + str(self.maxHealth))
        print("Your attack is: " + str(self.damage))
        print("Your defence is: " + str(self.defence))
        print("Your agility is: " + str(self.agility))
        print("Your gold is: " + str(self.gold))

bob = Player(15, 15, 5, 6, 7, 70)
spider = Enemy(10, 10, 2, 1, 5, 'silk')
spider.inspectStats()

我无法让这段代码工作,我在网上搜索并发现这个网站取得了轻微的成功:http: //www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and -inheritance-in-python/ 但是,代码似乎仍然无法正常工作。如果有人能告诉我应该如何继承,将不胜感激。(我知道会有一个敌人的子类,所以如果考虑到这一点会很有帮助)。

标签: pythonclass

解决方案


好的,所以,您的子类Enemy在方法定义中只需要 2 个参数selfdrop。因此,如果您想让它能够接收更多参数,则必须为其提供一些占位符。天真的方法只是将所有需要的参数写入到位。但是 lats 说将来您将扩展Character课程所采用的参数数量。为了使解决方案更友好,我们可以将*args变量添加为参数。这个变量(args 不是强制性名称,关键是*站在它前面的操作员)将“捕获”您在参数之后提供的所有drop参数。星号运算符不在乎您传递了多少参数。它将尝试尽可能多地服用。这些存储的参数现在可以解包像这样的父__init__方法:

class Enemy(Character):
    # the *args will "catch" all the positional 
    # parameters passed to this class 
    def __init__(self, drop, *args):

        # now we are using unpacking to 
        # apply all positional params holded in args to parent init method
        Character.__init__(self, *args)
        self.drop = drop

# Now You must remeber to pass the the init the  
# child argument which is drop 
# + all the parent class positional args (currentHealth, ...)

enemy = Enemy(True,...)

推荐阅读