#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/ 但是,该代码似乎仍然无法正常工作。如果有人能告诉我我应该如何继承,将不胜感激。 (我知道将会有一个敌人的子类,因此如果考虑到这一点会有所帮助。)
答案 0 :(得分:1)
好的,因此,您的子类Enemy
进入了方法定义,它只接受两个参数 self 和 drop 。
因此,如果要使其能够接收更多参数,则必须为其提供一些占位符。天真的方法是将所有需要的参数写到位。但是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,...)
答案 1 :(得分:1)
您的敌人 init 函数没有正确数量的参数。试试这个:
class Enemy(Character):
def __init__(self, currentHealth, maxHealth, damage, defence, agility, drop):
super(Enemy, self).__init__(currentHealth, maxHealth, damage, defence, agility)
self.drop = drop
有关“ super”关键字的更多详细信息,可以转到there