提出例外问题

2024-10-04 05:28:55 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

class longInputException(Exception):
    def __init__(self, length, max):
        Exception.__init__(self)
        self.length = len(length)
        self.max = max

try:
    max = 3
    s = raw_input('Enter something-->')
    if len(s) > max:
        raise longInputException(s, max)

except longInputException, x:
    print 'longInputException: the input was of length %d, \
was expecting less than or equal to %d' % (x.length, x.max)

else:
    print 'No exception was raised.'

我不明白的是为什么在longInputExceptionexcept语句中使用x。为什么不在替换元组中使用self?你知道吗


Tags: self密码inputleninitdefexceptionlength
3条回答

self是当前对象__init__()方法中的名称(因为您在__init__()的定义中提供了self作为第一个参数),因此在它之外是不可访问的。你知道吗

您也可以选择这样做(尽管这是而不是您应该做的事情,因为这可能会让人们混淆哪个变量是哪个变量):

except longInputException, self:
    print 'longInputException: the input was of length %d, \
was expecting less than or equal to %d' % (self.length, self.max)

else:
    print 'No exception was raised.'

它能回答你的问题吗?你知道吗

您可以通过阅读Python中的闭包和名称空间来了解更多信息。你知道吗

如果try…except语句位于另一个类的实例化中,并且在except语句中使用了“self”,则“self”将指实例化的类,而不是实例化的异常类。你知道吗

我想是因为这样你就不知道你指的是哪一个例外了。通常只在对象内部使用“self”。你知道吗

相关问题 更多 >