python - 我正在尝试优化一些类,但代码不起作用
问题描述
#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/ 但是,代码似乎仍然无法正常工作。如果有人能告诉我应该如何继承,将不胜感激。(我知道会有一个敌人的子类,所以如果考虑到这一点会很有帮助)。
解决方案
好的,所以,您的子类Enemy
在方法定义中只需要 2 个参数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,...)
推荐阅读
- javascript - 从 db.json 文件中检索数据并使用 javascript 将其添加到数组中
- awk - 重新排列以相同字符串开头的行
- html - 更改 Google 云端硬盘等内容
- xcode - ios模拟器卡在Virtual Box上的苹果标志上
- python - 如何将 Pika 与 Qt 集成?
- cucumber - 将 BDD 用作前端和后端作为一个项目的测试优先开发方法的流程是什么?
- mongodb - MongoDB查询引用的文档
- tree - 树状依赖图的 OpenCL 执行策略
- ruby-on-rails - 如何将强参数中的嵌套属性与 has_many 关联合并
- clojure - Clojure 中原语和盒装原语的示例