鱼C论坛

 找回密码
 立即注册
查看: 2250|回复: 1

[技术交流] 《零基础入门学习python》038笔记:类的继承

[复制链接]
发表于 2017-9-7 16:32:56 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 汪蛋 于 2017-9-7 21:37 编辑



知识点一:超厉害的super
class Ball:
    def __init__(self):
        self.color = 'yellow'

    def hello(self):
        print("Hello, this ball is %s" % self.color)

class BallA(Ball):
    def __init__(self):
        print("This ball is A")
      运行上面一段代码,会发现,BallA类虽然继承了Ball类,但是由于子类的__init__函数覆盖了基类的__init__,导致在BallA中并没有给self.color赋值,也就是BallA无法正常继承hello函数。可以有两种办法解决这个问题,Ball类不变,将BallA做如下改进:
# 方法一:
class BallA(Ball):
    def __init__(self):
        Ball.__init__(self)
        print("This ball is A")
# 方法二:
class BallA(Ball):
    def __init__(self):
        super().__init__()
        print("This ball is A")
      super的好处在于,当基类为多个时,仍然只需要这一条语句就可以解决了,而方法一则需要针对每一个基类写一条。是不是很厉害丫~~~


知识点二:多重继承
class BallA:
    def hello1(self):
        print("This ball is A")

class BallB:
    def hello2(self):
        print("This ball is A")

class C(BallA, BallB):
    pass

c = C()
c.hello1()
c.hello2()
      如果BallA和BallB中的hello函数名设为同一个,那么只会输出BallA中的hello。

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-4-19 13:48:22 | 显示全部楼层
class BallA:
    def __init__(self):
        self.color = "yellow"
    def hello(self):
        print("This ball is A")

class BallB:
    def __init__(self):
        self.weight = 10
    def hello(self):
        print("This ball is B")

class C(BallA, BallB):
    def __init__(self):
        super().__init__()
        BallB.__init__(self)

c = C()
c.color,c.weight

如果不写BallB.__init__(self)
c.weight 就会报错哎,,,光写super().__init__()不行额
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-18 14:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表