|
发表于 2023-2-23 09:29:17
|
显示全部楼层
第一个问题:
除非你想得到的结果是它们拼接后的字符串,否则不应该换成 str
- >>> class New_int(int):
- ... def __add__(self,other):
- ... return str(self) + str(other)
- ...
- >>> a = New_int(1)
- >>> b = New_int(2)
- >>> a + b
- '12'
- >>>
复制代码
你改成 str 后还是得到 3 的话,你可能是没有重新实例化
第二个问题:括号内可以不用 int,但是不能直接用 self + other,
因为 self 就是 New_int 类型,它在进行加法的时候会去调用 New_int 的 __add__ 方法,
然后在 New_int 的 __add__ 方法里面又去进行加法,这样就形成无限递归了,所以不能直接用 self 来加
如果你不用 int() 转成 int 类型的话,也可以去调用父类也就是 int 的 __add__ 方法,下面三种方式都是可以的
- class New_int(int):
- def __add__(self,other):
- return super().__add__(other)
复制代码
- class New_int(int):
- def __add__(self,other):
- return int(self).__add__(other)
复制代码
- class New_int(int):
- def __add__(self,other):
- return int.__add__(self, other)
复制代码
第三个问题:
这里不定义 __init__ 方法,是因为不需要对它的初始化进行个性化定制,所以就让它使用从父类继承过来的 __init__ 方法
|
|