1.单继承
所谓的单继承就是⼀个⼦类只有⼀个⽗类。⼦类会继承⽗类所有的属性和⽅法。
通过单继承,子类可以获取父类所有的成员,也可以自己添加新的成员,同时还可以改写继承自父类的方法。例如,
class PlayGame:
def __init__(self, gamename, gametype, gamescore, player):
self.gamename = gamename
self.gametype = gametype
self.gamescore = gamescore
self.__player = player
def __str__(self):
return "游戏测评"
def play(self):
print("game start")
def comment(self):
print("good game")
def __playername(self):
return self.__player
class ConsolePlayGame(PlayGame):
pass
这里子类ConsolePlayGame继承了父类PlayGame,子类ConsolePlayGame具有父类的一切方法和属性。例如,
dmc5 = ConsolePlayGame("Devil May Cry5", "act", 10, "Forseti")
print(dmc5.__dict__)
dmc5.play()
dmc5.comment()
执行结果如下,
{'gamename': 'Devil May Cry5', 'gametype': 'act', 'gamescore': 10, '_PlayGame__player': 'Forseti'}
game start
good game
如果我们想要在不改变父类属性的情况下,增加新的属性。我们有几种方法来实现。
写法一,
class ConsolePlayGame(PlayGame):
def __init__(self, gamename, gametype, gamescore, player, console):
self.gamename = gamename
self.gametype = gametype
self.gamescore = gamescore
self.__player = player
self.console = console # 增加新的属性
写法二,
class ConsolePlayGame(PlayGame):
def __init__(self, gamename, gametype, gamescore, player, console):
super().__init__(gamename, gametype, gamescore, player) # 继承父类属性
self.console = console # 增加新的属性
写法三,
class ConsolePlayGame(PlayGame):
def __init__(self, gamename, gametype, gamescore, player, console):
PlayGame.__init__(self, gamename, gametype, gamescore, player) # 继承父类属性
self.console = console # 增加新的属性
子类也可以增加新的方法或者修改父类方法,
class ConsolePlayGame(PlayGame):
def __init__(self, gamename, gametype, gamescore, player, console):
super().__init__(gamename, gametype, gamescore, player)
self.console = console
def platform(self, console): # 增加新的方法
return console
def comment(self):
super().comment() # 调用父类方法
print("评测平台:{}".format(self.console)) # 修改父类方法
dmc5 = ConsolePlayGame("Devil May Cry5", "act", 10, "Forseti", "all")
print(dmc5.platform())
dmc5.comment()
执行结果如下,
all
good game
评测平台:all