python中的单继承

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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值