鱼C论坛

 找回密码
 立即注册
查看: 908|回复: 6

关于__new__方法的一个问题

[复制链接]
发表于 2019-2-16 10:42:06 | 显示全部楼层 |阅读模式
10鱼币
  1. class Nint(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)
复制代码



如上代码
Nint(123)可以得出结果。
可是实例化对象后为什么就不行了?
比如a = Nint()
a(123)就会出现错误,提示说无法调用Nint()函数,这是为什么?怎么解决?原理是什么?

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

使用道具 举报

发表于 2019-2-16 11:13:04 | 显示全部楼层
你都已经实例化了,没有给传参的接口
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-2-16 11:36:59 | 显示全部楼层
  1. >>> class Nint(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.         
  10. >>> a = Nint(123)
  11. >>> a
  12. 123
  13. >>> a(123)
  14. Traceback (most recent call last):
  15.   File "<pyshell#4>", line 1, in <module>
  16.     a(123)
  17. TypeError: 'Nint' object is not callable
  18. >>>
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-2-16 11:53:43 | 显示全部楼层
塔利班 发表于 2019-2-16 11:13
你都已经实例化了,没有给传参的接口

有什么解决的办法吗?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-2-16 17:03:38 | 显示全部楼层
  1. class Nint(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.    
  10.     def __call__(self, arg = 0):
  11.         print(arg)
复制代码
  1. >>>
  2. ================== RESTART: C:\Users\admin\Desktop\test.py ==================
  3. >>> a = Nint(123)
  4. >>> a(123)
  5. 123
  6. >>>
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-2-16 18:13:18 | 显示全部楼层
Nint 继承的int , 跟int 区别在于int 不能传入到字母的字符串,而Nint 可以。 除此之外,跟int 一样。a=Nint(123),  所以a(123)=Nint(123)(123) 是没有意义的吧,就像不存在 int(123)(123) 一样  
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-16 13:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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