鱼C论坛

 找回密码
 立即注册
查看: 2710|回复: 2

构造函数问题

[复制链接]
发表于 2022-12-30 23:21:38 | 显示全部楼层 |阅读模式

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

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

x
  1. class Nstr(int):
  2.     def __new__(cls, arg=0):
  3.         if isinstance(arg, str):
  4.             total = 0
  5.             for each in arg:
  6.                 total += ord(each)
  7.             arg = total
  8.         return int.__new__(cls, arg)
复制代码

int.__new__是什么意思int是哪里来的
这里为什么要int.__new__(cls, arg)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-12-30 23:50:33 | 显示全部楼层
首先你在定义Nstr类的时候,class Nstr(int): 表示 int 类为 Nstr 的父类
int.__new__,这里的 int 就是父类 int, 利用int基类调用__new__方法。
return int.__new__(cls, arg)中arg元素已经替换成total值了,通过 int.__new__(cls, arg)可以得到arg的返回值,并且使得返回值是类的实例化对象
你如果直接使用return total,虽然可以得到同样的值,但是返回的是一个int类型的数据,并不是Nstr类型的数据。
  1. class Nstr(int):
  2.     def __new__(cls, arg=0):
  3.         if isinstance(arg, str):
  4.             total = 0
  5.             for each in arg:
  6.                 total += ord(each)
  7.             arg = total
  8.         return int.__new__(cls, arg)

  9. class Ns(int):
  10.     def __new__(cls, arg=0):
  11.         if isinstance(arg, str):
  12.             total = 0
  13.             for each in arg:
  14.                 total += ord(each)
  15.             arg = total
  16.         return total
  17. a = Ns("fishc")
  18. a
  19. 525
  20. type(a)
  21. <class 'int'>
  22. s = Nstr("fishc")
  23. type(s)
  24. <class '__main__.Nstr'>
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-1-1 16:15:44 | 显示全部楼层
lxping 发表于 2022-12-30 23:50
首先你在定义Nstr类的时候,class Nstr(int): 表示 int 类为 Nstr 的父类
int.__new__,这里的 int 就是父 ...

利用int基类调用__new__方法
请问这句话的意思是调用了int类里面的__new__方法吗
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-9 10:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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