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