must be an instance of Class or of a class derived from it The second form is a

Must be an instance of class or of a class derived

This preview shows page 106 - 108 out of 135 pages.

must be an instance of Class or of a class derived from it. The second form is a shorthand for: 第一种形式中, instance 必须是 Class 或其派生类的一个实例。 第二种形式是以下形式的简写 raise instance . __class__, instance A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around --- an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order: 发生的异常其类型如果是 except 子句中列出的类,或者是其派生 类,那么它们就是相符的(反过来说- -发生的异常其类型如果是异常子句中列 出的类的基类,它们就不相符)。例如,以下代码会按顺序打印 B,C,D class B : pass class C (B): pass class D (C): pass for c in [B, C, D]: try : raise c() except D: print "D" except C: print "C" except B: print "B" Note that if the except clauses were reversed (with except B first), it would have printed B, B, B --- the first matching except clause is triggered. 要注意的是如果异常子句的顺序颠倒过来( execpt B 在最前),它就会打印 B,B,B--第一个匹配的 异常被触发。 100 Chapter 9. Classes 类
Image of page 106
Python Tutorial, Release 2.7 When an error message is printed for an unhandled exception, the exception's class name is printed, then a colon and a space, and finally the instance converted to a string using the built-in function str() . 打印一个异常类的错误信息时,先打印类名,然后是一个空格、一个冒号,然后 是用内置函数 str() 类转换得到的完整字符串。 9.9 Iterators 迭代器 By now you have probably noticed that most container objects can be looped over using a for statement: 现在你可能注意到大多数容器对象都可以用 for 遍历 for element in [ 1 , 2 , 3 ]: print element for element in ( 1 , 2 , 3 ): print element for key in { 'one' : 1 , 'two' : 2 }: print key for char in "123" : print char for line in open ( "myfile.txt" ): print line This style of access is clear, concise, and convenient. The use of iterators pervades and unifies Python. Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method next() which accesses elements in the container one at a time. When there are no more elements, next() raises a StopIteration exception which tells the for loop to terminate. This example shows how it all works: 这种形式的访问清晰、简洁、方便。迭代器的用法在 Python 中普遍而且统一。 在后台, for 语句在容器 对象中调用 iter() 。 该函数返 回一个定义了 next() 方法的迭代器对象,它在容器中逐一访问元素。 没 有后续的元素时, next() 抛出一个 StopIteration 异常通知 for 语句循环结束。以下是其工作原理 的示例 >>> s = 'abc' >>> it = iter (s) >>> it < iterator object at 0x00A1DB50 > >>> it . next() 'a' >>> it . next() 'b' >>> it . next() 'c' >>> it . next() Traceback (most recent call last): File " < stdin > " , line 1 , in ?
Image of page 107
Image of page 108

You've reached the end of your free preview.

Want to read all 135 pages?

  • Fall '16
  • Shell

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture