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