Python 创建从super()类中提取变量的子类时出现问题
我对python有点陌生,目前正在练习类、子类和super()方法。 我一直在用Python创建一个小型RPG(或者至少是基本概念),我创建了基类,但似乎无法提取子类中的数据 以下是相关代码:Python 创建从super()类中提取变量的子类时出现问题,python,class,subclass,super,Python,Class,Subclass,Super,我对python有点陌生,目前正在练习类、子类和super()方法。 我一直在用Python创建一个小型RPG(或者至少是基本概念),我创建了基类,但似乎无法提取子类中的数据 以下是相关代码: class base_human: def __init__(self, health, magic, speed): self.health = health self.magic = magic self.speed = speed ## Is
class base_human:
def __init__(self, health, magic, speed):
self.health = health
self.magic = magic
self.speed = speed
## Is the base class
class Warrior(base_human):
def __init__(self, name):
self.name = name
super().__init__(self, health, magic, speed)
## Is my sub class
base_human = base_human(10, 10, 10)
Brian = Warrior("Brian")
print(Brian.health)
print(Brian.name)
## Is the final print to test.
我当前遇到以下错误:
Traceback (most recent call last):
File "/Users/zuikis/Desktop/PI Projects/Classes/RPG 2.py", line 48, in <module>
Brian = Warrior("Brian")
File "/Users/zuikis/Desktop/PI Projects/Classes/RPG 2.py", line 32, in __init__
super().__init__(self, health, magic, speed)
NameError: name 'health' is not defined
回溯(最近一次呼叫最后一次):
文件“/Users/zuikis/Desktop/PI Projects/Classes/RPG 2.py”,第48行,在
布莱恩=勇士(“布莱恩”)
文件“/Users/zuikis/Desktop/PI Projects/Classes/RPG 2.py”,第32行,在__
超级()。\uuuu初始化(自我、健康、魔法、速度)
NameError:未定义名称“health”
感谢您的帮助,请原谅我,如果我在帖子的格式上犯了错误,任何进一步的建议都会受到欢迎。非常感谢。战士。方法需要获取基本的所有参数。
方法需要获取基本的所有参数。
方法可以在调用超级()时传递这些参数。
然后,您需要在创建战士时提供所有这些值:
Brian = Warrior("Brian", 10, 20, 5)
另一方面,如果所有战士都以相同的属性开始,您可以在super()
调用中硬编码它们
class Warrior:
def __init__(self, name):
super().__init__(10, 20, 5)
self.name = name
目前,你的人类职业从哪里获得健康、魔法和速度
没错,它没有得到他们,这就是为什么它在抱怨。你的战士职业应该有
def __init__(self, name, health, magic, speed):
看看类定义
class Warrior(base_human):
def __init__(self, name):
self.name = name
super().__init__(self, health, magic, speed)
您在哪里通过health
或magic
或speed
?不在哪里。它们都没有定义。你需要写作
class Warrior(base_human):
def __init__(self, name, health, magic, speed):
super().__init__(health, magic, speed)
self.name = name
谢谢你,在阅读了更多的代码并进行了一些实验之后,我得到了我想要的结果。
class Warrior(base_human):
def __init__(self, name, health, magic, speed):
super().__init__(health, magic, speed)
self.name = name