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