鱼C论坛

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

42课 课后练习求助

[复制链接]
发表于 2017-3-31 10:07:38 | 显示全部楼层 |阅读模式

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

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

x
  1. 2. 定义一个类 Nstr,当该类的实例对象间发生的加、减、乘、除运算时,将该对象的所有字符串的 ASCII 码之和进行计算。
  2. >>> a = Nstr('FishC')
  3. >>> b = Nstr('love')
  4. >>> a + b
  5. 899
  6. >>> a - b
  7. 23
  8. >>> a * b
  9. 201918
  10. >>> a / b
  11. 1.052511415525114
  12. >>> a // b
  13. 1

  14. class Nstr:
  15.     def __init__(self, arg=''):
  16.         if isinstance(arg, str):
  17.             self.total = 0
  18.             for each in arg:
  19.                 self.total += ord(each)
  20.         else:
  21.             print("参数错误!")

  22.     def __add__(self, other):
  23.         return self.total + other.total

  24.     def __sub__(self, other):
  25.         return self.total - other.total

  26.     def __mul__(self, other):
  27.         return self.total * other.total

  28.     def __truediv__(self, other):
  29.         return self.total / other.total

  30.     def __floordiv__(self, other):
  31.         return self.total // other.total
  32. 当然你也可以这么做:
  33. class Nstr(int):
  34.     def __new__(cls, arg=0):
  35.         if isinstance(arg, str):
  36.             total = 0
  37.             for each in arg:
  38.                 total += ord(each)
  39.             arg = total
  40.         return int.__new__(cls, arg)
复制代码


想求教一下 两段 代码的 具体的区别是什么?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-4-2 11:38:39 | 显示全部楼层
__new__是每个类实例化时会自动调用的方法,返回的是实例对象
__init__是每个类实例化后会自动调用的方法,对实例对象进行一定的处理
  1. class a():
  2.     def __new__(cls, arg=0):
  3.         print('new')
  4.     def __init__(self):
  5.         print('init')
  6. A= a()
复制代码

用这个例子去理解下
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-25 22:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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