这是我的密码:
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.'
我不明白的是为什么在longInputException
的except
语句中使用x
。为什么不在替换元组中使用self
?你知道吗
self
是当前对象在__init__()
方法中的名称(因为您在__init__()
的定义中提供了self
作为第一个参数),因此在它之外是不可访问的。你知道吗您也可以选择这样做(尽管这是而不是您应该做的事情,因为这可能会让人们混淆哪个变量是哪个变量):
它能回答你的问题吗?你知道吗
您可以通过阅读Python中的闭包和名称空间来了解更多信息。你知道吗
如果try…except语句位于另一个类的实例化中,并且在except语句中使用了“self”,则“self”将指实例化的类,而不是实例化的异常类。你知道吗
我想是因为这样你就不知道你指的是哪一个例外了。通常只在对象内部使用“self”。你知道吗
相关问题 更多 >
编程相关推荐