鱼C论坛

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

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

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

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

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

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



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

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

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


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

  4. class BallB:
  5.     def hello2(self):
  6.         print("This ball is A")

  7. class C(BallA, BallB):
  8.     pass

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

本帖被以下淘专辑推荐:

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

使用道具 举报

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

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

  11. class C(BallA, BallB):
  12.     def __init__(self):
  13.         super().__init__()
  14.         BallB.__init__(self)

  15. c = C()
  16. c.color,c.weight
复制代码


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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-20 22:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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