注册 登录
编程论坛 Python论坛

有个python的小程序,解释下

fenghelong 发布于 2012-04-13 19:15, 1805 次点击
程序代码:
class ShortInputException(Exception):
    '''a user-defined exception class.'''
    def __int__(self,length,atleast):
        Exception.__int__(self)
        self.length=length
        self.atleast=atleast
try:
    s=raw_input('enter something-->')
    if len(s)<3:
        raise ShortInputException(len(s),3)
except EOFError:
    print '\nwhy did you do an EOF on me?'
except ShortInputException,x:
    print 'ShortInputException:The input was of length %d,\
          was expectiing at least %d
' %(x.length,x.atleast)
else:
    print 'no exception was raised.'
代码中的except ShortInputException,x:其中x前面的都好代表什么意思。
3 回复
#2
为Jay沉沦2012-04-13 20:01
ShortInputException是用户定义的一个异常的类,它是Exception的子类,
def __int__(self,length,atleast):
        Exception.__int__(self)
        self.length=length
        self.atleast=atleast
这一段是对类的对象的初始化,类似于构造函数。

raise ShortInputException(len(s),3)
在Python中,要想引发异常,最简单的形式就是输入关键字raise
执行raise语句时,Python会创建指定的异常类的一个对象。
raise语句还可指定对异常对象进行初始化的参数。
#3
岁月无真2012-04-15 21:08
正在学习中。
#4
快乐出发02202012-04-30 00:28
不错,我正想回答的了。。。
1