|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1
>>> class Try_int(int):
def __add__(self, other):
return self + other
>>> a = Try_int(3)
>>> b = Try_int(2)
>>> a + b
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
a + b
File "<pyshell#30>", line 3, in __add__
return self + other
File "<pyshell#30>", line 3, in __add__
return self + other
File "<pyshell#30>", line 3, in __add__
return self + other
[Previous line repeated 327 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
2
>>> class Try_int(int):
def __add__(self, other):
return int(self) + int(other) #还是没太理解,为啥转化整形之后就可以出结果,相加的不是方法吗
>>> a = Try_int(3)
>>> b = Try_int(2)
>>> a + b
5
本帖最后由 ba21 于 2017-7-24 11:11 编辑
>>> class Try_int(int):
def __add__(self, other):
return self + other
这里你用Try__int重写了int的__add__方法;
>>> a = Try_int(3)
>>> b = Try_int(2)
>>> a + b
返回的是 self + other,然后 又是 a + b 就陷入了无限递归,意思就是这里只要给合理的退出这个递归的代码就不会了。
return int(self) + int(other) 为什么加了int就正常了?
加了int就是把这句 int(self) + int(other) 交给了int父类去处理了;
return self + other 其实就好比 return Try_int(self) + Try_int(other) 自己又调用了自己,但是你又没有写退出这个递归的代码
注:加法不一定要用+ ;四则运算符的操作在编程里面有很多其它的方法可以实现。这段问题代码如果换做别的方法就不存在递归了
|
|