/Doc/tutorial/classes.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 806 lines · 626 code · 180 blank · 0 comment · 0 complexity · a71088642c65321d9f473db4443d5ce0 MD5 · raw file

  1. .. _tut-classes:
  2. *******
  3. Classes
  4. *******
  5. Python's class mechanism adds classes to the language with a minimum of new
  6. syntax and semantics. It is a mixture of the class mechanisms found in C++ and
  7. Modula-3. As is true for modules, classes in Python do not put an absolute
  8. barrier between definition and user, but rather rely on the politeness of the
  9. user not to "break into the definition." The most important features of classes
  10. are retained with full power, however: the class inheritance mechanism allows
  11. multiple base classes, a derived class can override any methods of its base
  12. class or classes, and a method can call the method of a base class with the same
  13. name. Objects can contain an arbitrary amount of private data.
  14. In C++ terminology, all class members (including the data members) are *public*,
  15. and all member functions are *virtual*. There are no special constructors or
  16. destructors. As in Modula-3, there are no shorthands for referencing the
  17. object's members from its methods: the method function is declared with an
  18. explicit first argument representing the object, which is provided implicitly by
  19. the call. As in Smalltalk, classes themselves are objects, albeit in the wider
  20. sense of the word: in Python, all data types are objects. This provides
  21. semantics for importing and renaming. Unlike C++ and Modula-3, built-in types
  22. can be used as base classes for extension by the user. Also, like in C++ but
  23. unlike in Modula-3, most built-in operators with special syntax (arithmetic
  24. operators, subscripting etc.) can be redefined for class instances.
  25. .. _tut-terminology:
  26. A Word About Terminology
  27. ========================
  28. Lacking universally accepted terminology to talk about classes, I will make
  29. occasional use of Smalltalk and C++ terms. (I would use Modula-3 terms, since
  30. its object-oriented semantics are closer to those of Python than C++, but I
  31. expect that few readers have heard of it.)
  32. Objects have individuality, and multiple names (in multiple scopes) can be bound
  33. to the same object. This is known as aliasing in other languages. This is
  34. usually not appreciated on a first glance at Python, and can be safely ignored
  35. when dealing with immutable basic types (numbers, strings, tuples). However,
  36. aliasing has an (intended!) effect on the semantics of Python code involving
  37. mutable objects such as lists, dictionaries, and most types representing
  38. entities outside the program (files, windows, etc.). This is usually used to
  39. the benefit of the program, since aliases behave like pointers in some respects.
  40. For example, passing an object is cheap since only a pointer is passed by the
  41. implementation; and if a function modifies an object passed as an argument, the
  42. caller will see the change --- this eliminates the need for two different
  43. argument passing mechanisms as in Pascal.
  44. .. _tut-scopes:
  45. Python Scopes and Name Spaces
  46. =============================
  47. Before introducing classes, I first have to tell you something about Python's
  48. scope rules. Class definitions play some neat tricks with namespaces, and you
  49. need to know how scopes and namespaces work to fully understand what's going on.
  50. Incidentally, knowledge about this subject is useful for any advanced Python
  51. programmer.
  52. Let's begin with some definitions.
  53. A *namespace* is a mapping from names to objects. Most namespaces are currently
  54. implemented as Python dictionaries, but that's normally not noticeable in any
  55. way (except for performance), and it may change in the future. Examples of
  56. namespaces are: the set of built-in names (functions such as :func:`abs`, and
  57. built-in exception names); the global names in a module; and the local names in
  58. a function invocation. In a sense the set of attributes of an object also form
  59. a namespace. The important thing to know about namespaces is that there is
  60. absolutely no relation between names in different namespaces; for instance, two
  61. different modules may both define a function "maximize" without confusion ---
  62. users of the modules must prefix it with the module name.
  63. By the way, I use the word *attribute* for any name following a dot --- for
  64. example, in the expression ``z.real``, ``real`` is an attribute of the object
  65. ``z``. Strictly speaking, references to names in modules are attribute
  66. references: in the expression ``modname.funcname``, ``modname`` is a module
  67. object and ``funcname`` is an attribute of it. In this case there happens to be
  68. a straightforward mapping between the module's attributes and the global names
  69. defined in the module: they share the same namespace! [#]_
  70. Attributes may be read-only or writable. In the latter case, assignment to
  71. attributes is possible. Module attributes are writable: you can write
  72. ``modname.the_answer = 42``. Writable attributes may also be deleted with the
  73. :keyword:`del` statement. For example, ``del modname.the_answer`` will remove
  74. the attribute :attr:`the_answer` from the object named by ``modname``.
  75. Name spaces are created at different moments and have different lifetimes. The
  76. namespace containing the built-in names is created when the Python interpreter
  77. starts up, and is never deleted. The global namespace for a module is created
  78. when the module definition is read in; normally, module namespaces also last
  79. until the interpreter quits. The statements executed by the top-level
  80. invocation of the interpreter, either read from a script file or interactively,
  81. are considered part of a module called :mod:`__main__`, so they have their own
  82. global namespace. (The built-in names actually also live in a module; this is
  83. called :mod:`__builtin__`.)
  84. The local namespace for a function is created when the function is called, and
  85. deleted when the function returns or raises an exception that is not handled
  86. within the function. (Actually, forgetting would be a better way to describe
  87. what actually happens.) Of course, recursive invocations each have their own
  88. local namespace.
  89. A *scope* is a textual region of a Python program where a namespace is directly
  90. accessible. "Directly accessible" here means that an unqualified reference to a
  91. name attempts to find the name in the namespace.
  92. Although scopes are determined statically, they are used dynamically. At any
  93. time during execution, there are at least three nested scopes whose namespaces
  94. are directly accessible: the innermost scope, which is searched first, contains
  95. the local names; the namespaces of any enclosing functions, which are searched
  96. starting with the nearest enclosing scope; the middle scope, searched next,
  97. contains the current module's global names; and the outermost scope (searched
  98. last) is the namespace containing built-in names.
  99. If a name is declared global, then all references and assignments go directly to
  100. the middle scope containing the module's global names. Otherwise, all variables
  101. found outside of the innermost scope are read-only (an attempt to write to such
  102. a variable will simply create a *new* local variable in the innermost scope,
  103. leaving the identically named outer variable unchanged).
  104. Usually, the local scope references the local names of the (textually) current
  105. function. Outside functions, the local scope references the same namespace as
  106. the global scope: the module's namespace. Class definitions place yet another
  107. namespace in the local scope.
  108. It is important to realize that scopes are determined textually: the global
  109. scope of a function defined in a module is that module's namespace, no matter
  110. from where or by what alias the function is called. On the other hand, the
  111. actual search for names is done dynamically, at run time --- however, the
  112. language definition is evolving towards static name resolution, at "compile"
  113. time, so don't rely on dynamic name resolution! (In fact, local variables are
  114. already determined statically.)
  115. A special quirk of Python is that -- if no :keyword:`global`
  116. statement is in effect -- assignments to names always go
  117. into the innermost scope. Assignments do not copy data --- they just bind names
  118. to objects. The same is true for deletions: the statement ``del x`` removes the
  119. binding of ``x`` from the namespace referenced by the local scope. In fact, all
  120. operations that introduce new names use the local scope: in particular, import
  121. statements and function definitions bind the module or function name in the
  122. local scope. (The :keyword:`global` statement can be used to indicate that
  123. particular variables live in the global scope.)
  124. .. _tut-firstclasses:
  125. A First Look at Classes
  126. =======================
  127. Classes introduce a little bit of new syntax, three new object types, and some
  128. new semantics.
  129. .. _tut-classdefinition:
  130. Class Definition Syntax
  131. -----------------------
  132. The simplest form of class definition looks like this::
  133. class ClassName:
  134. <statement-1>
  135. .
  136. .
  137. .
  138. <statement-N>
  139. Class definitions, like function definitions (:keyword:`def` statements) must be
  140. executed before they have any effect. (You could conceivably place a class
  141. definition in a branch of an :keyword:`if` statement, or inside a function.)
  142. In practice, the statements inside a class definition will usually be function
  143. definitions, but other statements are allowed, and sometimes useful --- we'll
  144. come back to this later. The function definitions inside a class normally have
  145. a peculiar form of argument list, dictated by the calling conventions for
  146. methods --- again, this is explained later.
  147. When a class definition is entered, a new namespace is created, and used as the
  148. local scope --- thus, all assignments to local variables go into this new
  149. namespace. In particular, function definitions bind the name of the new
  150. function here.
  151. When a class definition is left normally (via the end), a *class object* is
  152. created. This is basically a wrapper around the contents of the namespace
  153. created by the class definition; we'll learn more about class objects in the
  154. next section. The original local scope (the one in effect just before the class
  155. definition was entered) is reinstated, and the class object is bound here to the
  156. class name given in the class definition header (:class:`ClassName` in the
  157. example).
  158. .. _tut-classobjects:
  159. Class Objects
  160. -------------
  161. Class objects support two kinds of operations: attribute references and
  162. instantiation.
  163. *Attribute references* use the standard syntax used for all attribute references
  164. in Python: ``obj.name``. Valid attribute names are all the names that were in
  165. the class's namespace when the class object was created. So, if the class
  166. definition looked like this::
  167. class MyClass:
  168. """A simple example class"""
  169. i = 12345
  170. def f(self):
  171. return 'hello world'
  172. then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, returning
  173. an integer and a function object, respectively. Class attributes can also be
  174. assigned to, so you can change the value of ``MyClass.i`` by assignment.
  175. :attr:`__doc__` is also a valid attribute, returning the docstring belonging to
  176. the class: ``"A simple example class"``.
  177. Class *instantiation* uses function notation. Just pretend that the class
  178. object is a parameterless function that returns a new instance of the class.
  179. For example (assuming the above class)::
  180. x = MyClass()
  181. creates a new *instance* of the class and assigns this object to the local
  182. variable ``x``.
  183. The instantiation operation ("calling" a class object) creates an empty object.
  184. Many classes like to create objects with instances customized to a specific
  185. initial state. Therefore a class may define a special method named
  186. :meth:`__init__`, like this::
  187. def __init__(self):
  188. self.data = []
  189. When a class defines an :meth:`__init__` method, class instantiation
  190. automatically invokes :meth:`__init__` for the newly-created class instance. So
  191. in this example, a new, initialized instance can be obtained by::
  192. x = MyClass()
  193. Of course, the :meth:`__init__` method may have arguments for greater
  194. flexibility. In that case, arguments given to the class instantiation operator
  195. are passed on to :meth:`__init__`. For example, ::
  196. >>> class Complex:
  197. ... def __init__(self, realpart, imagpart):
  198. ... self.r = realpart
  199. ... self.i = imagpart
  200. ...
  201. >>> x = Complex(3.0, -4.5)
  202. >>> x.r, x.i
  203. (3.0, -4.5)
  204. .. _tut-instanceobjects:
  205. Instance Objects
  206. ----------------
  207. Now what can we do with instance objects? The only operations understood by
  208. instance objects are attribute references. There are two kinds of valid
  209. attribute names, data attributes and methods.
  210. *data attributes* correspond to "instance variables" in Smalltalk, and to "data
  211. members" in C++. Data attributes need not be declared; like local variables,
  212. they spring into existence when they are first assigned to. For example, if
  213. ``x`` is the instance of :class:`MyClass` created above, the following piece of
  214. code will print the value ``16``, without leaving a trace::
  215. x.counter = 1
  216. while x.counter < 10:
  217. x.counter = x.counter * 2
  218. print x.counter
  219. del x.counter
  220. The other kind of instance attribute reference is a *method*. A method is a
  221. function that "belongs to" an object. (In Python, the term method is not unique
  222. to class instances: other object types can have methods as well. For example,
  223. list objects have methods called append, insert, remove, sort, and so on.
  224. However, in the following discussion, we'll use the term method exclusively to
  225. mean methods of class instance objects, unless explicitly stated otherwise.)
  226. .. index:: object: method
  227. Valid method names of an instance object depend on its class. By definition,
  228. all attributes of a class that are function objects define corresponding
  229. methods of its instances. So in our example, ``x.f`` is a valid method
  230. reference, since ``MyClass.f`` is a function, but ``x.i`` is not, since
  231. ``MyClass.i`` is not. But ``x.f`` is not the same thing as ``MyClass.f`` --- it
  232. is a *method object*, not a function object.
  233. .. _tut-methodobjects:
  234. Method Objects
  235. --------------
  236. Usually, a method is called right after it is bound::
  237. x.f()
  238. In the :class:`MyClass` example, this will return the string ``'hello world'``.
  239. However, it is not necessary to call a method right away: ``x.f`` is a method
  240. object, and can be stored away and called at a later time. For example::
  241. xf = x.f
  242. while True:
  243. print xf()
  244. will continue to print ``hello world`` until the end of time.
  245. What exactly happens when a method is called? You may have noticed that
  246. ``x.f()`` was called without an argument above, even though the function
  247. definition for :meth:`f` specified an argument. What happened to the argument?
  248. Surely Python raises an exception when a function that requires an argument is
  249. called without any --- even if the argument isn't actually used...
  250. Actually, you may have guessed the answer: the special thing about methods is
  251. that the object is passed as the first argument of the function. In our
  252. example, the call ``x.f()`` is exactly equivalent to ``MyClass.f(x)``. In
  253. general, calling a method with a list of *n* arguments is equivalent to calling
  254. the corresponding function with an argument list that is created by inserting
  255. the method's object before the first argument.
  256. If you still don't understand how methods work, a look at the implementation can
  257. perhaps clarify matters. When an instance attribute is referenced that isn't a
  258. data attribute, its class is searched. If the name denotes a valid class
  259. attribute that is a function object, a method object is created by packing
  260. (pointers to) the instance object and the function object just found together in
  261. an abstract object: this is the method object. When the method object is called
  262. with an argument list, it is unpacked again, a new argument list is constructed
  263. from the instance object and the original argument list, and the function object
  264. is called with this new argument list.
  265. .. _tut-remarks:
  266. Random Remarks
  267. ==============
  268. .. These should perhaps be placed more carefully...
  269. Data attributes override method attributes with the same name; to avoid
  270. accidental name conflicts, which may cause hard-to-find bugs in large programs,
  271. it is wise to use some kind of convention that minimizes the chance of
  272. conflicts. Possible conventions include capitalizing method names, prefixing
  273. data attribute names with a small unique string (perhaps just an underscore), or
  274. using verbs for methods and nouns for data attributes.
  275. Data attributes may be referenced by methods as well as by ordinary users
  276. ("clients") of an object. In other words, classes are not usable to implement
  277. pure abstract data types. In fact, nothing in Python makes it possible to
  278. enforce data hiding --- it is all based upon convention. (On the other hand,
  279. the Python implementation, written in C, can completely hide implementation
  280. details and control access to an object if necessary; this can be used by
  281. extensions to Python written in C.)
  282. Clients should use data attributes with care --- clients may mess up invariants
  283. maintained by the methods by stamping on their data attributes. Note that
  284. clients may add data attributes of their own to an instance object without
  285. affecting the validity of the methods, as long as name conflicts are avoided ---
  286. again, a naming convention can save a lot of headaches here.
  287. There is no shorthand for referencing data attributes (or other methods!) from
  288. within methods. I find that this actually increases the readability of methods:
  289. there is no chance of confusing local variables and instance variables when
  290. glancing through a method.
  291. Often, the first argument of a method is called ``self``. This is nothing more
  292. than a convention: the name ``self`` has absolutely no special meaning to
  293. Python. (Note, however, that by not following the convention your code may be
  294. less readable to other Python programmers, and it is also conceivable that a
  295. *class browser* program might be written that relies upon such a convention.)
  296. Any function object that is a class attribute defines a method for instances of
  297. that class. It is not necessary that the function definition is textually
  298. enclosed in the class definition: assigning a function object to a local
  299. variable in the class is also ok. For example::
  300. # Function defined outside the class
  301. def f1(self, x, y):
  302. return min(x, x+y)
  303. class C:
  304. f = f1
  305. def g(self):
  306. return 'hello world'
  307. h = g
  308. Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to
  309. function objects, and consequently they are all methods of instances of
  310. :class:`C` --- ``h`` being exactly equivalent to ``g``. Note that this practice
  311. usually only serves to confuse the reader of a program.
  312. Methods may call other methods by using method attributes of the ``self``
  313. argument::
  314. class Bag:
  315. def __init__(self):
  316. self.data = []
  317. def add(self, x):
  318. self.data.append(x)
  319. def addtwice(self, x):
  320. self.add(x)
  321. self.add(x)
  322. Methods may reference global names in the same way as ordinary functions. The
  323. global scope associated with a method is the module containing the class
  324. definition. (The class itself is never used as a global scope!) While one
  325. rarely encounters a good reason for using global data in a method, there are
  326. many legitimate uses of the global scope: for one thing, functions and modules
  327. imported into the global scope can be used by methods, as well as functions and
  328. classes defined in it. Usually, the class containing the method is itself
  329. defined in this global scope, and in the next section we'll find some good
  330. reasons why a method would want to reference its own class!
  331. Each value is an object, and therefore has a *class* (also called its *type*).
  332. It is stored as ``object.__class__``.
  333. .. _tut-inheritance:
  334. Inheritance
  335. ===========
  336. Of course, a language feature would not be worthy of the name "class" without
  337. supporting inheritance. The syntax for a derived class definition looks like
  338. this::
  339. class DerivedClassName(BaseClassName):
  340. <statement-1>
  341. .
  342. .
  343. .
  344. <statement-N>
  345. The name :class:`BaseClassName` must be defined in a scope containing the
  346. derived class definition. In place of a base class name, other arbitrary
  347. expressions are also allowed. This can be useful, for example, when the base
  348. class is defined in another module::
  349. class DerivedClassName(modname.BaseClassName):
  350. Execution of a derived class definition proceeds the same as for a base class.
  351. When the class object is constructed, the base class is remembered. This is
  352. used for resolving attribute references: if a requested attribute is not found
  353. in the class, the search proceeds to look in the base class. This rule is
  354. applied recursively if the base class itself is derived from some other class.
  355. There's nothing special about instantiation of derived classes:
  356. ``DerivedClassName()`` creates a new instance of the class. Method references
  357. are resolved as follows: the corresponding class attribute is searched,
  358. descending down the chain of base classes if necessary, and the method reference
  359. is valid if this yields a function object.
  360. Derived classes may override methods of their base classes. Because methods
  361. have no special privileges when calling other methods of the same object, a
  362. method of a base class that calls another method defined in the same base class
  363. may end up calling a method of a derived class that overrides it. (For C++
  364. programmers: all methods in Python are effectively ``virtual``.)
  365. An overriding method in a derived class may in fact want to extend rather than
  366. simply replace the base class method of the same name. There is a simple way to
  367. call the base class method directly: just call ``BaseClassName.methodname(self,
  368. arguments)``. This is occasionally useful to clients as well. (Note that this
  369. only works if the base class is defined or imported directly in the global
  370. scope.)
  371. Python has two built-in functions that work with inheritance:
  372. * Use :func:`isinstance` to check an object's type: ``isinstance(obj, int)``
  373. will be ``True`` only if ``obj.__class__`` is :class:`int` or some class
  374. derived from :class:`int`.
  375. * Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)``
  376. is ``True`` since :class:`bool` is a subclass of :class:`int`. However,
  377. ``issubclass(unicode, str)`` is ``False`` since :class:`unicode` is not a
  378. subclass of :class:`str` (they only share a common ancestor,
  379. :class:`basestring`).
  380. .. _tut-multiple:
  381. Multiple Inheritance
  382. --------------------
  383. Python supports a limited form of multiple inheritance as well. A class
  384. definition with multiple base classes looks like this::
  385. class DerivedClassName(Base1, Base2, Base3):
  386. <statement-1>
  387. .
  388. .
  389. .
  390. <statement-N>
  391. For old-style classes, the only rule is depth-first, left-to-right. Thus, if an
  392. attribute is not found in :class:`DerivedClassName`, it is searched in
  393. :class:`Base1`, then (recursively) in the base classes of :class:`Base1`, and
  394. only if it is not found there, it is searched in :class:`Base2`, and so on.
  395. (To some people breadth first --- searching :class:`Base2` and :class:`Base3`
  396. before the base classes of :class:`Base1` --- looks more natural. However, this
  397. would require you to know whether a particular attribute of :class:`Base1` is
  398. actually defined in :class:`Base1` or in one of its base classes before you can
  399. figure out the consequences of a name conflict with an attribute of
  400. :class:`Base2`. The depth-first rule makes no differences between direct and
  401. inherited attributes of :class:`Base1`.)
  402. For :term:`new-style class`\es, the method resolution order changes dynamically
  403. to support cooperative calls to :func:`super`. This approach is known in some
  404. other multiple-inheritance languages as call-next-method and is more powerful
  405. than the super call found in single-inheritance languages.
  406. With new-style classes, dynamic ordering is necessary because all cases of
  407. multiple inheritance exhibit one or more diamond relationships (where one at
  408. least one of the parent classes can be accessed through multiple paths from the
  409. bottommost class). For example, all new-style classes inherit from
  410. :class:`object`, so any case of multiple inheritance provides more than one path
  411. to reach :class:`object`. To keep the base classes from being accessed more
  412. than once, the dynamic algorithm linearizes the search order in a way that
  413. preserves the left-to-right ordering specified in each class, that calls each
  414. parent only once, and that is monotonic (meaning that a class can be subclassed
  415. without affecting the precedence order of its parents). Taken together, these
  416. properties make it possible to design reliable and extensible classes with
  417. multiple inheritance. For more detail, see
  418. http://www.python.org/download/releases/2.3/mro/.
  419. .. _tut-private:
  420. Private Variables
  421. =================
  422. There is limited support for class-private identifiers. Any identifier of the
  423. form ``__spam`` (at least two leading underscores, at most one trailing
  424. underscore) is textually replaced with ``_classname__spam``, where ``classname``
  425. is the current class name with leading underscore(s) stripped. This mangling is
  426. done without regard to the syntactic position of the identifier, so it can be
  427. used to define class-private instance and class variables, methods, variables
  428. stored in globals, and even variables stored in instances. private to this class
  429. on instances of *other* classes. Truncation may occur when the mangled name
  430. would be longer than 255 characters. Outside classes, or when the class name
  431. consists of only underscores, no mangling occurs.
  432. Name mangling is intended to give classes an easy way to define "private"
  433. instance variables and methods, without having to worry about instance variables
  434. defined by derived classes, or mucking with instance variables by code outside
  435. the class. Note that the mangling rules are designed mostly to avoid accidents;
  436. it still is possible for a determined soul to access or modify a variable that
  437. is considered private. This can even be useful in special circumstances, such
  438. as in the debugger, and that's one reason why this loophole is not closed.
  439. (Buglet: derivation of a class with the same name as the base class makes use of
  440. private variables of the base class possible.)
  441. Notice that code passed to ``exec``, ``eval()`` or ``execfile()`` does not
  442. consider the classname of the invoking class to be the current class; this is
  443. similar to the effect of the ``global`` statement, the effect of which is
  444. likewise restricted to code that is byte-compiled together. The same
  445. restriction applies to ``getattr()``, ``setattr()`` and ``delattr()``, as well
  446. as when referencing ``__dict__`` directly.
  447. .. _tut-odds:
  448. Odds and Ends
  449. =============
  450. Sometimes it is useful to have a data type similar to the Pascal "record" or C
  451. "struct", bundling together a few named data items. An empty class definition
  452. will do nicely::
  453. class Employee:
  454. pass
  455. john = Employee() # Create an empty employee record
  456. # Fill the fields of the record
  457. john.name = 'John Doe'
  458. john.dept = 'computer lab'
  459. john.salary = 1000
  460. A piece of Python code that expects a particular abstract data type can often be
  461. passed a class that emulates the methods of that data type instead. For
  462. instance, if you have a function that formats some data from a file object, you
  463. can define a class with methods :meth:`read` and :meth:`readline` that get the
  464. data from a string buffer instead, and pass it as an argument.
  465. .. (Unfortunately, this technique has its limitations: a class can't define
  466. operations that are accessed by special syntax such as sequence subscripting
  467. or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will
  468. not cause the interpreter to read further input from it.)
  469. Instance method objects have attributes, too: ``m.im_self`` is the instance
  470. object with the method :meth:`m`, and ``m.im_func`` is the function object
  471. corresponding to the method.
  472. .. _tut-exceptionclasses:
  473. Exceptions Are Classes Too
  474. ==========================
  475. User-defined exceptions are identified by classes as well. Using this mechanism
  476. it is possible to create extensible hierarchies of exceptions.
  477. There are two new valid (semantic) forms for the raise statement::
  478. raise Class, instance
  479. raise instance
  480. In the first form, ``instance`` must be an instance of :class:`Class` or of a
  481. class derived from it. The second form is a shorthand for::
  482. raise instance.__class__, instance
  483. A class in an except clause is compatible with an exception if it is the same
  484. class or a base class thereof (but not the other way around --- an except clause
  485. listing a derived class is not compatible with a base class). For example, the
  486. following code will print B, C, D in that order::
  487. class B:
  488. pass
  489. class C(B):
  490. pass
  491. class D(C):
  492. pass
  493. for c in [B, C, D]:
  494. try:
  495. raise c()
  496. except D:
  497. print "D"
  498. except C:
  499. print "C"
  500. except B:
  501. print "B"
  502. Note that if the except clauses were reversed (with ``except B`` first), it
  503. would have printed B, B, B --- the first matching except clause is triggered.
  504. When an error message is printed for an unhandled exception, the exception's
  505. class name is printed, then a colon and a space, and finally the instance
  506. converted to a string using the built-in function :func:`str`.
  507. .. _tut-iterators:
  508. Iterators
  509. =========
  510. By now you have probably noticed that most container objects can be looped over
  511. using a :keyword:`for` statement::
  512. for element in [1, 2, 3]:
  513. print element
  514. for element in (1, 2, 3):
  515. print element
  516. for key in {'one':1, 'two':2}:
  517. print key
  518. for char in "123":
  519. print char
  520. for line in open("myfile.txt"):
  521. print line
  522. This style of access is clear, concise, and convenient. The use of iterators
  523. pervades and unifies Python. Behind the scenes, the :keyword:`for` statement
  524. calls :func:`iter` on the container object. The function returns an iterator
  525. object that defines the method :meth:`next` which accesses elements in the
  526. container one at a time. When there are no more elements, :meth:`next` raises a
  527. :exc:`StopIteration` exception which tells the :keyword:`for` loop to terminate.
  528. This example shows how it all works::
  529. >>> s = 'abc'
  530. >>> it = iter(s)
  531. >>> it
  532. <iterator object at 0x00A1DB50>
  533. >>> it.next()
  534. 'a'
  535. >>> it.next()
  536. 'b'
  537. >>> it.next()
  538. 'c'
  539. >>> it.next()
  540. Traceback (most recent call last):
  541. File "<stdin>", line 1, in ?
  542. it.next()
  543. StopIteration
  544. Having seen the mechanics behind the iterator protocol, it is easy to add
  545. iterator behavior to your classes. Define a :meth:`__iter__` method which
  546. returns an object with a :meth:`next` method. If the class defines
  547. :meth:`next`, then :meth:`__iter__` can just return ``self``::
  548. class Reverse:
  549. "Iterator for looping over a sequence backwards"
  550. def __init__(self, data):
  551. self.data = data
  552. self.index = len(data)
  553. def __iter__(self):
  554. return self
  555. def next(self):
  556. if self.index == 0:
  557. raise StopIteration
  558. self.index = self.index - 1
  559. return self.data[self.index]
  560. >>> for char in Reverse('spam'):
  561. ... print char
  562. ...
  563. m
  564. a
  565. p
  566. s
  567. .. _tut-generators:
  568. Generators
  569. ==========
  570. :term:`Generator`\s are a simple and powerful tool for creating iterators. They
  571. are written like regular functions but use the :keyword:`yield` statement
  572. whenever they want to return data. Each time :meth:`next` is called, the
  573. generator resumes where it left-off (it remembers all the data values and which
  574. statement was last executed). An example shows that generators can be trivially
  575. easy to create::
  576. def reverse(data):
  577. for index in range(len(data)-1, -1, -1):
  578. yield data[index]
  579. >>> for char in reverse('golf'):
  580. ... print char
  581. ...
  582. f
  583. l
  584. o
  585. g
  586. Anything that can be done with generators can also be done with class based
  587. iterators as described in the previous section. What makes generators so
  588. compact is that the :meth:`__iter__` and :meth:`next` methods are created
  589. automatically.
  590. Another key feature is that the local variables and execution state are
  591. automatically saved between calls. This made the function easier to write and
  592. much more clear than an approach using instance variables like ``self.index``
  593. and ``self.data``.
  594. In addition to automatic method creation and saving program state, when
  595. generators terminate, they automatically raise :exc:`StopIteration`. In
  596. combination, these features make it easy to create iterators with no more effort
  597. than writing a regular function.
  598. .. _tut-genexps:
  599. Generator Expressions
  600. =====================
  601. Some simple generators can be coded succinctly as expressions using a syntax
  602. similar to list comprehensions but with parentheses instead of brackets. These
  603. expressions are designed for situations where the generator is used right away
  604. by an enclosing function. Generator expressions are more compact but less
  605. versatile than full generator definitions and tend to be more memory friendly
  606. than equivalent list comprehensions.
  607. Examples::
  608. >>> sum(i*i for i in range(10)) # sum of squares
  609. 285
  610. >>> xvec = [10, 20, 30]
  611. >>> yvec = [7, 5, 3]
  612. >>> sum(x*y for x,y in zip(xvec, yvec)) # dot product
  613. 260
  614. >>> from math import pi, sin
  615. >>> sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91))
  616. >>> unique_words = set(word for line in page for word in line.split())
  617. >>> valedictorian = max((student.gpa, student.name) for student in graduates)
  618. >>> data = 'golf'
  619. >>> list(data[i] for i in range(len(data)-1,-1,-1))
  620. ['f', 'l', 'o', 'g']
  621. .. rubric:: Footnotes
  622. .. [#] Except for one thing. Module objects have a secret read-only attribute called
  623. :attr:`__dict__` which returns the dictionary used to implement the module's
  624. namespace; the name :attr:`__dict__` is an attribute but not a global name.
  625. Obviously, using this violates the abstraction of namespace implementation, and
  626. should be restricted to things like post-mortem debuggers.