|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class Nstr(str):
- def __str__(self):
- print('str方法被调用了!')
- return '__str__:{}'.format(self)
- def __repr__(self):
- print('repr方法被调用了!')
- return '__repr__:{}'.format(self)
- >>>s = Nstr('hello')
- repr方法被调用了!
- str方法被调用了!
- str方法被调用了!
- str方法被调用了!
- ...
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- File "<stdin>", line 7, in __repr__
- File "<stdin>", line 4, in __str__
- File "<stdin>", line 4, in __str__
- File "<stdin>", line 4, in __str__
- [Previous line repeated 245 more times]
- File "<stdin>", line 3, in __str__
- RecursionError: maximum recursion depth exceeded while calling a Python object
复制代码
为什么会出现递归错误?
因为你 '__repr__:{}'.format(self) 会调用 str(self),而 __str__ 方法中的 '__str__:{}'.format(self) 又会调用 str(self),无限递归所以报错了。
这样即可:
- class Nstr(str):
- def __str__(self):
- print('str方法被调用了!')
- return '__str__'
- def __repr__(self):
- print('repr方法被调用了!')
- return '__repr__'
复制代码
|
|