鱼C论坛

 找回密码
 立即注册
查看: 2365|回复: 5

关于类为什么要继承?

[复制链接]
发表于 2020-9-27 15:46:35 | 显示全部楼层 |阅读模式

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

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

x
[课后作业] 第042讲 中的有的继承int,有的继承str,有的又不继承
https://fishc.com.cn/forum.php?m ... peid%26typeid%3D398

  1. 第一段代码:
  2. class Nstr(str):
  3.     def __lshift__(self, other):
  4.         return self[other:] + self[:other]

  5.     def __rshift__(self, other):
  6.         return self[-other:] + self[:-other]

  7. 第二段代码:
  8. class Nstr:
  9.     def __init__(self, arg=''):
  10.         if isinstance(arg, str):
  11.             self.total = 0
  12.             for each in arg:
  13.                 self.total += ord(each)
  14.         else:
  15.             print("参数错误!")

  16.     def __add__(self, other):
  17.         return self.total + other.total

  18.     def __sub__(self, other):
  19.         return self.total - other.total

  20.     def __mul__(self, other):
  21.         return self.total * other.total

  22.     def __truediv__(self, other):
  23.         return self.total / other.total

  24.     def __floordiv__(self, other):
  25.         return self.total // other.total

  26. 第三段代码:
  27. class Nstr(int):
  28.     def __new__(cls, arg=0):
  29.         if isinstance(arg, str):
  30.             total = 0
  31.             for each in arg:
  32.                 total += ord(each)
  33.             arg = total
  34.         return int.__new__(cls, arg)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-9-27 15:56:20 | 显示全部楼层
可以减少代码量
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-9-27 18:45:27 | 显示全部楼层
继不继承看具体需求
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-9-27 22:38:09 From FishC Mobile | 显示全部楼层
是否继承一个类主要看你的需求来决定。
如果说你写了一个类,里面有一些功能是别的类已经有的,他们的实现思路和实现过程都符合你的要求,这时候最省事的办法就只有两个。一个是直接把你需要的源代码复制过来,直接用。另一个就是用类的继承。把别的类的方法继承过来,你就可以直接用了。第一个方法的缺点是特别low,会有代码冗余的问题。第二个就省事多了。
另外就是子类可以继承多个父类,也就意味着一个子类可以用好几个父类的方法,这样除了节省代码以外,还能进行方法的组合产生新的方法。大大节省开发时间。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

头像被屏蔽
发表于 2020-9-28 06:54:44 | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-9-28 18:11:04 | 显示全部楼层
本帖最后由 月照梨花 于 2020-9-28 18:21 编辑
  1. class Nstr(str):
  2.     def __sub__(self, other):
  3.         return self.replace(other, '')
复制代码

如上这段代码 继承的str时 实参就必须是字符串? 继承int时实参就必须是整型? 那如果我想两者都能输入呢 可以的吗?

还有__add__这类的运算魔法方法,只能在继承str或int这类时才能调用?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-27 18:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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