|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class Nint(int):
- def __init__(self, arg):
- if isinstance(arg, str):
- self.result = 0
- for each in arg:
- self.result += ord(each)
- else:
- self.result = int(arg)
- def __repr__(self):
- return str(self.result)
- __str__ = __repr__
复制代码
为啥print(Nint(3))、print(Nint('32'))都行,但print(Nint('i love fishc'))就报错?
你继承了 int 类,导致 __new__ 创建实例化过程不能将非整数字符串转化为 int 对象而报错,所以你应该重写 __new__ 而不是 __init__
重写了 __new__ 如果直接设置返回的是 result 值,那么就不必设置 __repr__ 方法了,因为此时返回的是 int的实力对象了,而不是 Nint 了
正确代码:
- class Nint(int):
- def __new__(self, arg):
- if isinstance(arg, str):
- result = 0
- for each in arg:
- result += ord(each)
- else:
- result = int(arg)
- return result
- print(Nint(3))
- print(Nint('32'))
- print(Nint('i love fishc'))
复制代码
输出结果:
|
|