class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length, x.atleast)
我不明白这行的语法:except ShortInputException, x:
x在这里是为了什么?? 为什么它是一个物体???在
这条线有什么用?:Exception.__init__(self)
谢谢
ShortInputException(Exception)
将您的类ShortInputException
声明为Exception
的子类。Exception.__init__(self)
调用父类的构造函数。在except ShortInputException, x:
从doc:
在您的示例中,
x
是引发的异常对象。在捕获类ShortInputException的异常,并将异常对象的实例绑定到x
更常见的语法是
^{pr2}$如PEP3110所述,这是首选。除非需要支持python2.5,否则应该使用as版本。在
调用超级类的构造函数,该类是此用户定义类派生的类。在
相关问题 更多 >
编程相关推荐