异常代表类型:什么意思?

Don*_*sto 3 python

假设我有这个

try:
 #some code here
except Exception, e:
 print e
 print repr(e)
Run Code Online (Sandbox Code Playgroud)

从这段代码中,我得到

>>
>> <exceptions.Exception instance at 0x2aaaac3281b8>
Run Code Online (Sandbox Code Playgroud)

为什么我没有任何异常消息,而且第二条消息意味着什么?

Joh*_*nck 6

您有一个异常,该异常产生一个空str(即为str(e)空)。为什么不能从您发布的有限代码中得知原因,您必须查看回溯以查看异常的来源。

至于repr(),这是为了产生一个可能很丑陋的字符串,它允许对象的重建,而不是漂亮的印刷。这不是打印异常所需的内容。


owi*_*ebo 5

一个例外衍生对象是在抛出# some code here。这个对象有一个__str__返回空字符串或空格的__repr__方法,没有方法。

请参阅Python 帮助

class SomeClass(object):
  def __str__(self):
    # Compute the 'informal' string representation of an object.
    return 'Something useful'
  def __repr__(self):
    # Compute the 'official' string representation of an object. If at all possible, this should look like a valid
    # Python expression that could be used to recreate an object with the same value (given an appropriate environment).
    return 'SomeClass()'

o = SomeClass()

print o
print repr(o)
Run Code Online (Sandbox Code Playgroud)

输出;

  Something useful
  SomeClass()
Run Code Online (Sandbox Code Playgroud)