【发布时间】:2018-07-02 20:54:33
【问题描述】:
对 Python 非常陌生,试图创建一个可以创建任意数量军队的游戏,但每支军队都会预渲染士兵的名字。
我认为我需要使用超级初始化来真正减少重复代码,但我无法终生弄清楚如何让它工作。据我了解,我的类Army 应该是父类,RedArmy 和Scout 作为子类。我只是在努力理解super().__init__() 应该在哪里出现?
class Army:
def __init__(self):
self.color = None
self.scoutname = None
self.demomanname = None
self.medicname = None
def train_scout(self, weapon):
return Scout(self.color, self.scoutname, weapon)
class RedArmy(Army):
def __init__(self):
self.color = "Red"
self.scoutname = "Yankee"
self.demomanname = "Irish"
self.medicname = "Dutch"
class BlueArmy(Army):
pass
class Scout:
specialization = "fast captures"
def __init__(self, color, scoutname, weapon):
self.color = color
self.scoutname = scoutname
self.weapon = weapon
def introduce(self):
return (f'Hi I\'m {self.scoutname}, I do {self.specialization} and I wield a {self.weapon}')
my_army = RedArmy()
soldier_1 = my_army.train_scout("baseball bat")
print(soldier_1.introduce())
【问题讨论】:
-
注意:如果使用 Python-2.7,请将基类定义为
class Army(object),否则 super() 将不起作用。在 Python 3 上也可以使用newclass(object)。 -
@LeoK OP 显然使用的是 Python 3;如果没有,
super()无论如何都不会工作。教新手如何将新的、仅 Python-3 的代码编写为双版本代码会适得其反,因为这意味着错过了 Python 3 的所有改进。 -
@LeoK 如果使用 Python 2.7,
Scout.introduce中的 f-string 会导致语法错误。
标签: python inheritance