2011-02-01 76 views
4

有沒有在Python中拋出異常的str()可以str()在Python中失敗?

+1

文檔說什麼? – 2011-02-01 00:06:43

+2

@Mitch小麥:我首先看了這裏:http://docs.python.org/library/functions.html#str答案:什麼都沒有。 – 2011-02-01 02:14:29

回答

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)