有沒有在Python中拋出異常的str()
?可以str()在Python中失敗?
4
A
回答
14
是的,它可能會因自定義類:
>>> class C(object):
... def __str__(self):
... return 'oops: ' + oops
...
>>> c = C()
>>> str(c)
NameError: global name 'oops' is not defined
它甚至可以失敗某些內置的-in類,如unicode
:
>>> u = u'\xff'
>>> s = str(u)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0:
ordinal not in range(128)
3
這取決於你打電話給str()
的對象。每個對象都可以在__str__()
函數中定義它自己的實現,這很容易引發異常。
例子:
class A:
def __str__(self):
raise Exception
str(A())
8
是的,當然:
class A(object):
def __str__(self):
raise Exception
a = A()
str(a)
相關問題
- 1. 可以ConcurrentDictionary.TryAdd失敗?
- 2. str在Python中不可調用錯誤
- 3. 在Python中:'import sitecustomize'失敗;
- 4. os.system()在python中失敗
- 5. Python smtplib send_message()失敗,返回AttributeError:'str'對象沒有屬性'get_all'
- 6. 字節STR轉換失敗python3
- 7. shell命令從python失敗,從shell中可以正常工作
- 8. TypeError,'str'不可調用 - Python
- 9. Python str不可調用
- 10. 在Python中鉤住str .__ getitem__
- 11. Python glob失敗?
- 12. Python - 失敗u202c
- 13. python sqlite失敗
- 14. str參數在Python
- 15. 使用STR在Python
- 16. Python 3,如果str存在替換str
- 17. python中的getaddrinfo失敗
- 18. Python可變條件測試失敗
- 19. Python 2.5以datetime.strptime格式失敗
- 20. Mutalyzer py.test以python-magic錯誤失敗
- 21. Python單元測試以失敗告終
- 22. EXC_BAD_INSTRUCTION:task_thread失敗可可
- 23. 在Python 2.7中導入'urllib3.util'失敗?
- 24. 如何在setUpClass中失敗python unittest?
- 25. 如何在Python中返回失敗值
- 26. 爲什麼在Python中交換失敗?
- 27. Hadoop Streaming作業在python中失敗
- 28. PIL Image.save()函數在Blender中失敗python
- 29. 導入模塊CairoPlot在Python中失敗
- 30. 試圖在Python中使用yaml.load失敗
文檔說什麼? – 2011-02-01 00:06:43
@Mitch小麥:我首先看了這裏:http://docs.python.org/library/functions.html#str答案:什麼都沒有。 – 2011-02-01 02:14:29