blob: 08072a31a1294d239e4e5a001dbf56e895cb3845 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-classes:
2
3*******
4Classes
5*******
6
Georg Brandla1928282010-10-17 10:44:11 +00007Compared with other programming languages, Python's class mechanism adds classes
8with a minimum of new syntax and semantics. It is a mixture of the class
9mechanisms found in C++ and Modula-3. Python classes provide all the standard
10features of Object Oriented Programming: the class inheritance mechanism allows
Georg Brandl116aa622007-08-15 14:28:22 +000011multiple base classes, a derived class can override any methods of its base
12class or classes, and a method can call the method of a base class with the same
Georg Brandla1928282010-10-17 10:44:11 +000013name. Objects can contain arbitrary amounts and kinds of data. As is true for
14modules, classes partake of the dynamic nature of Python: they are created at
15runtime, and can be modified further after creation.
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
Georg Brandla1928282010-10-17 10:44:11 +000018*public* (except see below :ref:`tut-private`), and all member functions are
19*virtual*. As in Modula-3, there are no shorthands for referencing the object's
20members from its methods: the method function is declared with an explicit first
21argument representing the object, which is provided implicitly by the call. As
22in Smalltalk, classes themselves are objects. This provides semantics for
23importing and renaming. Unlike C++ and Modula-3, built-in types can be used as
24base classes for extension by the user. Also, like in C++, most built-in
25operators with special syntax (arithmetic operators, subscripting etc.) can be
26redefined for class instances.
Georg Brandl116aa622007-08-15 14:28:22 +000027
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
Georg Brandla6053b42009-09-01 08:11:14 +000054Python Scopes and Namespaces
55============================
Georg Brandl116aa622007-08-15 14:28:22 +000056
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
Georg Brandl17dafdc2010-08-02 20:44:34 +000068namespaces are: the set of built-in names (containing functions such as :func:`abs`, and
Georg Brandl116aa622007-08-15 14:28:22 +000069built-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
Georg Brandla6053b42009-09-01 08:11:14 +000090Namespaces are created at different moments and have different lifetimes. The
Georg Brandl116aa622007-08-15 14:28:22 +000091namespace 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
Georg Brandl3517e372009-08-13 11:55:03 +0000146function definitions bind the module or function name in the local scope.
Georg Brandlc5d98b42007-12-04 18:11:03 +0000147
148The :keyword:`global` statement can be used to indicate that particular
149variables live in the global scope and should be rebound there; the
150:keyword:`nonlocal` statement indicates that particular variables live in
151an enclosing scope and should be rebound there.
152
153.. _tut-scopeexample:
154
155Scopes and Namespaces Example
156-----------------------------
157
158This is an example demonstrating how to reference the different scopes and
159namespaces, and how :keyword:`global` and :keyword:`nonlocal` affect variable
160binding::
161
162 def scope_test():
163 def do_local():
164 spam = "local spam"
165 def do_nonlocal():
166 nonlocal spam
167 spam = "nonlocal spam"
168 def do_global():
169 global spam
170 spam = "global spam"
Georg Brandlc5d98b42007-12-04 18:11:03 +0000171 spam = "test spam"
172 do_local()
173 print("After local assignment:", spam)
174 do_nonlocal()
175 print("After nonlocal assignment:", spam)
176 do_global()
177 print("After global assignment:", spam)
178
179 scope_test()
180 print("In global scope:", spam)
181
Senthil Kumaran74d56572012-03-08 20:54:34 -0800182The output of the example code is:
183
184.. code-block:: none
Georg Brandlc5d98b42007-12-04 18:11:03 +0000185
186 After local assignment: test spam
187 After nonlocal assignment: nonlocal spam
188 After global assignment: nonlocal spam
189 In global scope: global spam
190
191Note how the *local* assignment (which is default) didn't change *scope_test*\'s
192binding of *spam*. The :keyword:`nonlocal` assignment changed *scope_test*\'s
193binding of *spam*, and the :keyword:`global` assignment changed the module-level
194binding.
195
196You can also see that there was no previous binding for *spam* before the
197:keyword:`global` assignment.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199
200.. _tut-firstclasses:
201
202A First Look at Classes
203=======================
204
205Classes introduce a little bit of new syntax, three new object types, and some
206new semantics.
207
208
209.. _tut-classdefinition:
210
211Class Definition Syntax
212-----------------------
213
214The simplest form of class definition looks like this::
215
216 class ClassName:
217 <statement-1>
218 .
219 .
220 .
221 <statement-N>
222
223Class definitions, like function definitions (:keyword:`def` statements) must be
224executed before they have any effect. (You could conceivably place a class
225definition in a branch of an :keyword:`if` statement, or inside a function.)
226
227In practice, the statements inside a class definition will usually be function
228definitions, but other statements are allowed, and sometimes useful --- we'll
229come back to this later. The function definitions inside a class normally have
230a peculiar form of argument list, dictated by the calling conventions for
231methods --- again, this is explained later.
232
233When a class definition is entered, a new namespace is created, and used as the
234local scope --- thus, all assignments to local variables go into this new
235namespace. In particular, function definitions bind the name of the new
236function here.
237
238When a class definition is left normally (via the end), a *class object* is
239created. This is basically a wrapper around the contents of the namespace
240created by the class definition; we'll learn more about class objects in the
241next section. The original local scope (the one in effect just before the class
242definition was entered) is reinstated, and the class object is bound here to the
243class name given in the class definition header (:class:`ClassName` in the
244example).
245
246
247.. _tut-classobjects:
248
249Class Objects
250-------------
251
252Class objects support two kinds of operations: attribute references and
253instantiation.
254
255*Attribute references* use the standard syntax used for all attribute references
256in Python: ``obj.name``. Valid attribute names are all the names that were in
257the class's namespace when the class object was created. So, if the class
258definition looked like this::
259
260 class MyClass:
Georg Brandl5d955ed2008-09-13 17:18:21 +0000261 """A simple example class"""
Georg Brandl116aa622007-08-15 14:28:22 +0000262 i = 12345
263 def f(self):
264 return 'hello world'
265
266then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, returning
267an integer and a function object, respectively. Class attributes can also be
268assigned to, so you can change the value of ``MyClass.i`` by assignment.
269:attr:`__doc__` is also a valid attribute, returning the docstring belonging to
270the class: ``"A simple example class"``.
271
272Class *instantiation* uses function notation. Just pretend that the class
273object is a parameterless function that returns a new instance of the class.
274For example (assuming the above class)::
275
276 x = MyClass()
277
278creates a new *instance* of the class and assigns this object to the local
279variable ``x``.
280
281The instantiation operation ("calling" a class object) creates an empty object.
282Many classes like to create objects with instances customized to a specific
283initial state. Therefore a class may define a special method named
284:meth:`__init__`, like this::
285
286 def __init__(self):
287 self.data = []
288
289When a class defines an :meth:`__init__` method, class instantiation
290automatically invokes :meth:`__init__` for the newly-created class instance. So
291in this example, a new, initialized instance can be obtained by::
292
293 x = MyClass()
294
295Of course, the :meth:`__init__` method may have arguments for greater
296flexibility. In that case, arguments given to the class instantiation operator
297are passed on to :meth:`__init__`. For example, ::
298
299 >>> class Complex:
300 ... def __init__(self, realpart, imagpart):
301 ... self.r = realpart
302 ... self.i = imagpart
Georg Brandl48310cd2009-01-03 21:18:54 +0000303 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000304 >>> x = Complex(3.0, -4.5)
305 >>> x.r, x.i
306 (3.0, -4.5)
307
308
309.. _tut-instanceobjects:
310
311Instance Objects
312----------------
313
314Now what can we do with instance objects? The only operations understood by
315instance objects are attribute references. There are two kinds of valid
316attribute names, data attributes and methods.
317
318*data attributes* correspond to "instance variables" in Smalltalk, and to "data
319members" in C++. Data attributes need not be declared; like local variables,
320they spring into existence when they are first assigned to. For example, if
321``x`` is the instance of :class:`MyClass` created above, the following piece of
322code will print the value ``16``, without leaving a trace::
323
324 x.counter = 1
325 while x.counter < 10:
326 x.counter = x.counter * 2
Guido van Rossum0616b792007-08-31 03:25:11 +0000327 print(x.counter)
Georg Brandl116aa622007-08-15 14:28:22 +0000328 del x.counter
329
330The other kind of instance attribute reference is a *method*. A method is a
331function that "belongs to" an object. (In Python, the term method is not unique
332to class instances: other object types can have methods as well. For example,
333list objects have methods called append, insert, remove, sort, and so on.
334However, in the following discussion, we'll use the term method exclusively to
335mean methods of class instance objects, unless explicitly stated otherwise.)
336
337.. index:: object: method
338
339Valid method names of an instance object depend on its class. By definition,
340all attributes of a class that are function objects define corresponding
341methods of its instances. So in our example, ``x.f`` is a valid method
342reference, since ``MyClass.f`` is a function, but ``x.i`` is not, since
343``MyClass.i`` is not. But ``x.f`` is not the same thing as ``MyClass.f`` --- it
344is a *method object*, not a function object.
345
346
347.. _tut-methodobjects:
348
349Method Objects
350--------------
351
352Usually, a method is called right after it is bound::
353
354 x.f()
355
356In the :class:`MyClass` example, this will return the string ``'hello world'``.
357However, it is not necessary to call a method right away: ``x.f`` is a method
358object, and can be stored away and called at a later time. For example::
359
360 xf = x.f
361 while True:
Guido van Rossum0616b792007-08-31 03:25:11 +0000362 print(xf())
Georg Brandl116aa622007-08-15 14:28:22 +0000363
364will continue to print ``hello world`` until the end of time.
365
366What exactly happens when a method is called? You may have noticed that
367``x.f()`` was called without an argument above, even though the function
368definition for :meth:`f` specified an argument. What happened to the argument?
369Surely Python raises an exception when a function that requires an argument is
370called without any --- even if the argument isn't actually used...
371
372Actually, you may have guessed the answer: the special thing about methods is
373that the object is passed as the first argument of the function. In our
374example, the call ``x.f()`` is exactly equivalent to ``MyClass.f(x)``. In
375general, calling a method with a list of *n* arguments is equivalent to calling
376the corresponding function with an argument list that is created by inserting
377the method's object before the first argument.
378
379If you still don't understand how methods work, a look at the implementation can
380perhaps clarify matters. When an instance attribute is referenced that isn't a
381data attribute, its class is searched. If the name denotes a valid class
382attribute that is a function object, a method object is created by packing
383(pointers to) the instance object and the function object just found together in
384an abstract object: this is the method object. When the method object is called
Georg Brandla6053b42009-09-01 08:11:14 +0000385with an argument list, a new argument list is constructed from the instance
386object and the argument list, and the function object is called with this new
387argument list.
Georg Brandl116aa622007-08-15 14:28:22 +0000388
389
390.. _tut-remarks:
391
392Random Remarks
393==============
394
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000395.. These should perhaps be placed more carefully...
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397Data attributes override method attributes with the same name; to avoid
398accidental name conflicts, which may cause hard-to-find bugs in large programs,
399it is wise to use some kind of convention that minimizes the chance of
400conflicts. Possible conventions include capitalizing method names, prefixing
401data attribute names with a small unique string (perhaps just an underscore), or
402using verbs for methods and nouns for data attributes.
403
404Data attributes may be referenced by methods as well as by ordinary users
405("clients") of an object. In other words, classes are not usable to implement
406pure abstract data types. In fact, nothing in Python makes it possible to
407enforce data hiding --- it is all based upon convention. (On the other hand,
408the Python implementation, written in C, can completely hide implementation
409details and control access to an object if necessary; this can be used by
410extensions to Python written in C.)
411
412Clients should use data attributes with care --- clients may mess up invariants
413maintained by the methods by stamping on their data attributes. Note that
414clients may add data attributes of their own to an instance object without
415affecting the validity of the methods, as long as name conflicts are avoided ---
416again, a naming convention can save a lot of headaches here.
417
418There is no shorthand for referencing data attributes (or other methods!) from
419within methods. I find that this actually increases the readability of methods:
420there is no chance of confusing local variables and instance variables when
421glancing through a method.
422
423Often, the first argument of a method is called ``self``. This is nothing more
424than a convention: the name ``self`` has absolutely no special meaning to
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000425Python. Note, however, that by not following the convention your code may be
Georg Brandl116aa622007-08-15 14:28:22 +0000426less readable to other Python programmers, and it is also conceivable that a
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000427*class browser* program might be written that relies upon such a convention.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
429Any function object that is a class attribute defines a method for instances of
430that class. It is not necessary that the function definition is textually
431enclosed in the class definition: assigning a function object to a local
432variable in the class is also ok. For example::
433
434 # Function defined outside the class
435 def f1(self, x, y):
436 return min(x, x+y)
437
438 class C:
439 f = f1
440 def g(self):
441 return 'hello world'
442 h = g
443
444Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to
445function objects, and consequently they are all methods of instances of
446:class:`C` --- ``h`` being exactly equivalent to ``g``. Note that this practice
447usually only serves to confuse the reader of a program.
448
449Methods may call other methods by using method attributes of the ``self``
450argument::
451
452 class Bag:
453 def __init__(self):
454 self.data = []
455 def add(self, x):
456 self.data.append(x)
457 def addtwice(self, x):
458 self.add(x)
459 self.add(x)
460
461Methods may reference global names in the same way as ordinary functions. The
Terry Jan Reedyea868d32012-01-11 14:54:34 -0500462global scope associated with a method is the module containing its
463definition. (A class is never used as a global scope.) While one
Georg Brandl116aa622007-08-15 14:28:22 +0000464rarely encounters a good reason for using global data in a method, there are
465many legitimate uses of the global scope: for one thing, functions and modules
466imported into the global scope can be used by methods, as well as functions and
467classes defined in it. Usually, the class containing the method is itself
468defined in this global scope, and in the next section we'll find some good
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000469reasons why a method would want to reference its own class.
Georg Brandl116aa622007-08-15 14:28:22 +0000470
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000471Each value is an object, and therefore has a *class* (also called its *type*).
472It is stored as ``object.__class__``.
473
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475.. _tut-inheritance:
476
477Inheritance
478===========
479
480Of course, a language feature would not be worthy of the name "class" without
481supporting inheritance. The syntax for a derived class definition looks like
482this::
483
484 class DerivedClassName(BaseClassName):
485 <statement-1>
486 .
487 .
488 .
489 <statement-N>
490
491The name :class:`BaseClassName` must be defined in a scope containing the
492derived class definition. In place of a base class name, other arbitrary
493expressions are also allowed. This can be useful, for example, when the base
494class is defined in another module::
495
496 class DerivedClassName(modname.BaseClassName):
497
498Execution of a derived class definition proceeds the same as for a base class.
499When the class object is constructed, the base class is remembered. This is
500used for resolving attribute references: if a requested attribute is not found
501in the class, the search proceeds to look in the base class. This rule is
502applied recursively if the base class itself is derived from some other class.
503
504There's nothing special about instantiation of derived classes:
505``DerivedClassName()`` creates a new instance of the class. Method references
506are resolved as follows: the corresponding class attribute is searched,
507descending down the chain of base classes if necessary, and the method reference
508is valid if this yields a function object.
509
510Derived classes may override methods of their base classes. Because methods
511have no special privileges when calling other methods of the same object, a
512method of a base class that calls another method defined in the same base class
513may end up calling a method of a derived class that overrides it. (For C++
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000514programmers: all methods in Python are effectively ``virtual``.)
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516An overriding method in a derived class may in fact want to extend rather than
517simply replace the base class method of the same name. There is a simple way to
518call the base class method directly: just call ``BaseClassName.methodname(self,
519arguments)``. This is occasionally useful to clients as well. (Note that this
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000520only works if the base class is accessible as ``BaseClassName`` in the global
Georg Brandl116aa622007-08-15 14:28:22 +0000521scope.)
522
Mark Dickinson934896d2009-02-21 20:59:32 +0000523Python has two built-in functions that work with inheritance:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000524
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000525* Use :func:`isinstance` to check an instance's type: ``isinstance(obj, int)``
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000526 will be ``True`` only if ``obj.__class__`` is :class:`int` or some class
527 derived from :class:`int`.
528
529* Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)``
530 is ``True`` since :class:`bool` is a subclass of :class:`int`. However,
Georg Brandl01ca04c2008-07-16 21:21:29 +0000531 ``issubclass(float, int)`` is ``False`` since :class:`float` is not a
532 subclass of :class:`int`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000533
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000534
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536.. _tut-multiple:
537
538Multiple Inheritance
539--------------------
540
Georg Brandl2d2590d2007-09-28 13:13:35 +0000541Python supports a form of multiple inheritance as well. A class definition with
542multiple base classes looks like this::
Georg Brandl116aa622007-08-15 14:28:22 +0000543
544 class DerivedClassName(Base1, Base2, Base3):
545 <statement-1>
546 .
547 .
548 .
549 <statement-N>
550
Georg Brandl2d2590d2007-09-28 13:13:35 +0000551For most purposes, in the simplest cases, you can think of the search for
552attributes inherited from a parent class as depth-first, left-to-right, not
553searching twice in the same class where there is an overlap in the hierarchy.
554Thus, if an attribute is not found in :class:`DerivedClassName`, it is searched
555for in :class:`Base1`, then (recursively) in the base classes of :class:`Base1`,
556and if it was not found there, it was searched for in :class:`Base2`, and so on.
Georg Brandl116aa622007-08-15 14:28:22 +0000557
Georg Brandl2d2590d2007-09-28 13:13:35 +0000558In fact, it is slightly more complex than that; the method resolution order
559changes dynamically to support cooperative calls to :func:`super`. This
560approach is known in some other multiple-inheritance languages as
561call-next-method and is more powerful than the super call found in
562single-inheritance languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000563
Georg Brandl85eb8c12007-08-31 16:33:38 +0000564Dynamic ordering is necessary because all cases of multiple inheritance exhibit
Georg Brandl9afde1c2007-11-01 20:32:30 +0000565one or more diamond relationships (where at least one of the parent classes
Georg Brandl85eb8c12007-08-31 16:33:38 +0000566can be accessed through multiple paths from the bottommost class). For example,
567all classes inherit from :class:`object`, so any case of multiple inheritance
568provides more than one path to reach :class:`object`. To keep the base classes
569from being accessed more than once, the dynamic algorithm linearizes the search
570order in a way that preserves the left-to-right ordering specified in each
571class, that calls each parent only once, and that is monotonic (meaning that a
572class can be subclassed without affecting the precedence order of its parents).
573Taken together, these properties make it possible to design reliable and
574extensible classes with multiple inheritance. For more detail, see
Georg Brandl116aa622007-08-15 14:28:22 +0000575http://www.python.org/download/releases/2.3/mro/.
576
577
578.. _tut-private:
579
580Private Variables
581=================
582
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000583"Private" instance variables that cannot be accessed except from inside an
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000584object don't exist in Python. However, there is a convention that is followed
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000585by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should
586be treated as a non-public part of the API (whether it is a function, a method
587or a data member). It should be considered an implementation detail and subject
588to change without notice.
Georg Brandl116aa622007-08-15 14:28:22 +0000589
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000590Since there is a valid use-case for class-private members (namely to avoid name
591clashes of names with names defined by subclasses), there is limited support for
592such a mechanism, called :dfn:`name mangling`. Any identifier of the form
593``__spam`` (at least two leading underscores, at most one trailing underscore)
594is textually replaced with ``_classname__spam``, where ``classname`` is the
595current class name with leading underscore(s) stripped. This mangling is done
Georg Brandldffc1b82009-08-13 12:58:30 +0000596without regard to the syntactic position of the identifier, as long as it
597occurs within the definition of a class.
Georg Brandl116aa622007-08-15 14:28:22 +0000598
Raymond Hettinger6ddefd72011-06-25 16:30:39 +0200599Name mangling is helpful for letting subclasses override methods without
600breaking intraclass method calls. For example::
601
Éric Araujo72db3452011-07-26 16:54:24 +0200602 class Mapping:
603 def __init__(self, iterable):
604 self.items_list = []
605 self.__update(iterable)
Raymond Hettinger6ddefd72011-06-25 16:30:39 +0200606
Éric Araujo72db3452011-07-26 16:54:24 +0200607 def update(self, iterable):
608 for item in iterable:
609 self.items_list.append(item)
Raymond Hettinger6ddefd72011-06-25 16:30:39 +0200610
Éric Araujo72db3452011-07-26 16:54:24 +0200611 __update = update # private copy of original update() method
Raymond Hettinger6ddefd72011-06-25 16:30:39 +0200612
Éric Araujo72db3452011-07-26 16:54:24 +0200613 class MappingSubclass(Mapping):
Raymond Hettinger6ddefd72011-06-25 16:30:39 +0200614
Éric Araujo72db3452011-07-26 16:54:24 +0200615 def update(self, keys, values):
616 # provides new signature for update()
617 # but does not break __init__()
618 for item in zip(keys, values):
619 self.items_list.append(item)
Raymond Hettinger6ddefd72011-06-25 16:30:39 +0200620
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000621Note that the mangling rules are designed mostly to avoid accidents; it still is
622possible to access or modify a variable that is considered private. This can
623even be useful in special circumstances, such as in the debugger.
624
Mark Dickinsoncf48e442010-07-12 09:37:40 +0000625Notice that code passed to ``exec()`` or ``eval()`` does not consider the
626classname of the invoking class to be the current class; this is similar to the
627effect of the ``global`` statement, the effect of which is likewise restricted
628to code that is byte-compiled together. The same restriction applies to
629``getattr()``, ``setattr()`` and ``delattr()``, as well as when referencing
630``__dict__`` directly.
Georg Brandl116aa622007-08-15 14:28:22 +0000631
632
633.. _tut-odds:
634
635Odds and Ends
636=============
637
638Sometimes it is useful to have a data type similar to the Pascal "record" or C
639"struct", bundling together a few named data items. An empty class definition
640will do nicely::
641
642 class Employee:
643 pass
644
645 john = Employee() # Create an empty employee record
646
647 # Fill the fields of the record
648 john.name = 'John Doe'
649 john.dept = 'computer lab'
650 john.salary = 1000
651
652A piece of Python code that expects a particular abstract data type can often be
653passed a class that emulates the methods of that data type instead. For
654instance, if you have a function that formats some data from a file object, you
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300655can define a class with methods :meth:`read` and :meth:`!readline` that get the
Georg Brandl116aa622007-08-15 14:28:22 +0000656data from a string buffer instead, and pass it as an argument.
657
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000658.. (Unfortunately, this technique has its limitations: a class can't define
659 operations that are accessed by special syntax such as sequence subscripting
660 or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will
661 not cause the interpreter to read further input from it.)
Georg Brandl116aa622007-08-15 14:28:22 +0000662
Christian Heimesff737952007-11-27 10:40:20 +0000663Instance method objects have attributes, too: ``m.__self__`` is the instance
664object with the method :meth:`m`, and ``m.__func__`` is the function object
Georg Brandl116aa622007-08-15 14:28:22 +0000665corresponding to the method.
666
667
668.. _tut-exceptionclasses:
669
670Exceptions Are Classes Too
671==========================
672
673User-defined exceptions are identified by classes as well. Using this mechanism
674it is possible to create extensible hierarchies of exceptions.
675
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000676There are two new valid (semantic) forms for the :keyword:`raise` statement::
Georg Brandl116aa622007-08-15 14:28:22 +0000677
Collin Winterbbc97122007-09-10 00:27:23 +0000678 raise Class
Georg Brandl116aa622007-08-15 14:28:22 +0000679
Collin Winterbbc97122007-09-10 00:27:23 +0000680 raise Instance
Georg Brandl116aa622007-08-15 14:28:22 +0000681
Collin Winterbbc97122007-09-10 00:27:23 +0000682In the first form, ``Class`` must be an instance of :class:`type` or of a
683class derived from it. The first form is a shorthand for::
Georg Brandl116aa622007-08-15 14:28:22 +0000684
Collin Winterbbc97122007-09-10 00:27:23 +0000685 raise Class()
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000687A class in an :keyword:`except` clause is compatible with an exception if it is
688the same class or a base class thereof (but not the other way around --- an
689except clause listing a derived class is not compatible with a base class). For
690example, the following code will print B, C, D in that order::
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Georg Brandlf5f26302008-08-08 06:50:56 +0000692 class B(Exception):
Georg Brandl116aa622007-08-15 14:28:22 +0000693 pass
694 class C(B):
695 pass
696 class D(C):
697 pass
698
Georg Brandl52d3e7e2011-03-07 08:31:52 +0100699 for cls in [B, C, D]:
Georg Brandl116aa622007-08-15 14:28:22 +0000700 try:
Georg Brandl52d3e7e2011-03-07 08:31:52 +0100701 raise cls()
Georg Brandl116aa622007-08-15 14:28:22 +0000702 except D:
Guido van Rossum0616b792007-08-31 03:25:11 +0000703 print("D")
Georg Brandl116aa622007-08-15 14:28:22 +0000704 except C:
Guido van Rossum0616b792007-08-31 03:25:11 +0000705 print("C")
Georg Brandl116aa622007-08-15 14:28:22 +0000706 except B:
Guido van Rossum0616b792007-08-31 03:25:11 +0000707 print("B")
Georg Brandl116aa622007-08-15 14:28:22 +0000708
709Note that if the except clauses were reversed (with ``except B`` first), it
710would have printed B, B, B --- the first matching except clause is triggered.
711
712When an error message is printed for an unhandled exception, the exception's
713class name is printed, then a colon and a space, and finally the instance
714converted to a string using the built-in function :func:`str`.
715
716
717.. _tut-iterators:
718
719Iterators
720=========
721
722By now you have probably noticed that most container objects can be looped over
723using a :keyword:`for` statement::
724
725 for element in [1, 2, 3]:
Guido van Rossum0616b792007-08-31 03:25:11 +0000726 print(element)
Georg Brandl116aa622007-08-15 14:28:22 +0000727 for element in (1, 2, 3):
Guido van Rossum0616b792007-08-31 03:25:11 +0000728 print(element)
Georg Brandl116aa622007-08-15 14:28:22 +0000729 for key in {'one':1, 'two':2}:
Guido van Rossum0616b792007-08-31 03:25:11 +0000730 print(key)
Georg Brandl116aa622007-08-15 14:28:22 +0000731 for char in "123":
Guido van Rossum0616b792007-08-31 03:25:11 +0000732 print(char)
Georg Brandl116aa622007-08-15 14:28:22 +0000733 for line in open("myfile.txt"):
Guido van Rossum0616b792007-08-31 03:25:11 +0000734 print(line)
Georg Brandl116aa622007-08-15 14:28:22 +0000735
736This style of access is clear, concise, and convenient. The use of iterators
737pervades and unifies Python. Behind the scenes, the :keyword:`for` statement
738calls :func:`iter` on the container object. The function returns an iterator
Ezio Melotti7fa82222012-10-12 13:42:08 +0300739object that defines the method :meth:`~iterator.__next__` which accesses
740elements in the container one at a time. When there are no more elements,
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300741:meth:`~iterator.__next__` raises a :exc:`StopIteration` exception which tells the
742:keyword:`for` loop to terminate. You can call the :meth:`~iterator.__next__` method
Ezio Melotti7fa82222012-10-12 13:42:08 +0300743using the :func:`next` built-in function; this example shows how it all works::
Georg Brandl116aa622007-08-15 14:28:22 +0000744
745 >>> s = 'abc'
746 >>> it = iter(s)
747 >>> it
748 <iterator object at 0x00A1DB50>
749 >>> next(it)
750 'a'
751 >>> next(it)
752 'b'
753 >>> next(it)
754 'c'
755 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000756 Traceback (most recent call last):
757 File "<stdin>", line 1, in ?
758 next(it)
759 StopIteration
760
761Having seen the mechanics behind the iterator protocol, it is easy to add
Georg Brandl06742552010-07-19 11:28:05 +0000762iterator behavior to your classes. Define an :meth:`__iter__` method which
Ezio Melotti7fa82222012-10-12 13:42:08 +0300763returns an object with a :meth:`~iterator.__next__` method. If the class
764defines :meth:`__next__`, then :meth:`__iter__` can just return ``self``::
Georg Brandl116aa622007-08-15 14:28:22 +0000765
766 class Reverse:
Georg Brandlda623ed2011-05-01 22:37:23 +0200767 """Iterator for looping over a sequence backwards."""
Georg Brandl116aa622007-08-15 14:28:22 +0000768 def __init__(self, data):
769 self.data = data
770 self.index = len(data)
771 def __iter__(self):
772 return self
773 def __next__(self):
774 if self.index == 0:
775 raise StopIteration
776 self.index = self.index - 1
777 return self.data[self.index]
778
Georg Brandl2cdee702011-05-01 22:34:31 +0200779::
780
Georg Brandl06742552010-07-19 11:28:05 +0000781 >>> rev = Reverse('spam')
782 >>> iter(rev)
783 <__main__.Reverse object at 0x00A1DB50>
784 >>> for char in rev:
Guido van Rossum0616b792007-08-31 03:25:11 +0000785 ... print(char)
Georg Brandl116aa622007-08-15 14:28:22 +0000786 ...
787 m
788 a
789 p
790 s
791
792
793.. _tut-generators:
794
795Generators
796==========
797
Georg Brandl9afde1c2007-11-01 20:32:30 +0000798:term:`Generator`\s are a simple and powerful tool for creating iterators. They
799are written like regular functions but use the :keyword:`yield` statement
800whenever they want to return data. Each time :func:`next` is called on it, the
801generator resumes where it left-off (it remembers all the data values and which
802statement was last executed). An example shows that generators can be trivially
803easy to create::
Georg Brandl116aa622007-08-15 14:28:22 +0000804
805 def reverse(data):
806 for index in range(len(data)-1, -1, -1):
807 yield data[index]
808
Georg Brandl2cdee702011-05-01 22:34:31 +0200809::
810
Georg Brandl116aa622007-08-15 14:28:22 +0000811 >>> for char in reverse('golf'):
Guido van Rossum0616b792007-08-31 03:25:11 +0000812 ... print(char)
Georg Brandl116aa622007-08-15 14:28:22 +0000813 ...
814 f
815 l
816 o
Georg Brandl06788c92009-01-03 21:31:47 +0000817 g
Georg Brandl116aa622007-08-15 14:28:22 +0000818
819Anything that can be done with generators can also be done with class based
820iterators as described in the previous section. What makes generators so
Ezio Melotti7fa82222012-10-12 13:42:08 +0300821compact is that the :meth:`__iter__` and :meth:`~generator.__next__` methods
822are created automatically.
Georg Brandl116aa622007-08-15 14:28:22 +0000823
824Another key feature is that the local variables and execution state are
825automatically saved between calls. This made the function easier to write and
826much more clear than an approach using instance variables like ``self.index``
827and ``self.data``.
828
829In addition to automatic method creation and saving program state, when
830generators terminate, they automatically raise :exc:`StopIteration`. In
831combination, these features make it easy to create iterators with no more effort
832than writing a regular function.
833
834
835.. _tut-genexps:
836
837Generator Expressions
838=====================
839
840Some simple generators can be coded succinctly as expressions using a syntax
841similar to list comprehensions but with parentheses instead of brackets. These
842expressions are designed for situations where the generator is used right away
843by an enclosing function. Generator expressions are more compact but less
844versatile than full generator definitions and tend to be more memory friendly
845than equivalent list comprehensions.
846
847Examples::
848
849 >>> sum(i*i for i in range(10)) # sum of squares
850 285
851
852 >>> xvec = [10, 20, 30]
853 >>> yvec = [7, 5, 3]
854 >>> sum(x*y for x,y in zip(xvec, yvec)) # dot product
855 260
856
857 >>> from math import pi, sin
Georg Brandlf6945182008-02-01 11:56:49 +0000858 >>> sine_table = {x: sin(x*pi/180) for x in range(0, 91)}
Georg Brandl116aa622007-08-15 14:28:22 +0000859
860 >>> unique_words = set(word for line in page for word in line.split())
861
862 >>> valedictorian = max((student.gpa, student.name) for student in graduates)
863
864 >>> data = 'golf'
Georg Brandle4ac7502007-09-03 07:10:24 +0000865 >>> list(data[i] for i in range(len(data)-1, -1, -1))
Georg Brandl116aa622007-08-15 14:28:22 +0000866 ['f', 'l', 'o', 'g']
867
868
869
870.. rubric:: Footnotes
871
872.. [#] Except for one thing. Module objects have a secret read-only attribute called
873 :attr:`__dict__` which returns the dictionary used to implement the module's
874 namespace; the name :attr:`__dict__` is an attribute but not a global name.
875 Obviously, using this violates the abstraction of namespace implementation, and
876 should be restricted to things like post-mortem debuggers.
877