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