~ubuntu-branches/ubuntu/lucid/python2.6/lucid

« back to all changes in this revision

Viewing changes to Doc/tutorial/classes.rst

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2010-03-11 13:30:19 UTC
  • mto: (10.1.13 sid)
  • mto: This revision was merged to the branch mainline in revision 44.
  • Revision ID: james.westby@ubuntu.com-20100311133019-sblbooa3uqrkoe70
Tags: upstream-2.6.5~rc2
ImportĀ upstreamĀ versionĀ 2.6.5~rc2

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
are retained with full power, however: the class inheritance mechanism allows
13
13
multiple base classes, a derived class can override any methods of its base
14
14
class or classes, and a method can call the method of a base class with the same
15
 
name.  Objects can contain an arbitrary amount of private data.
 
15
name.  Objects can contain an arbitrary amount of data.
16
16
 
17
17
In C++ terminology, all class members (including the data members) are *public*,
18
 
and all member functions are *virtual*.  There are no special constructors or
19
 
destructors.  As in Modula-3, there are no shorthands for referencing the
20
 
object's members from its methods: the method function is declared with an
21
 
explicit first argument representing the object, which is provided implicitly by
22
 
the call.  As in Smalltalk, classes themselves are objects, albeit in the wider
23
 
sense of the word: in Python, all data types are objects.  This provides
24
 
semantics for importing and renaming.  Unlike  C++ and Modula-3, built-in types
25
 
can be used as base classes for extension by the user.  Also, like in C++ but
26
 
unlike in Modula-3, most built-in operators with special syntax (arithmetic
 
18
and all member functions are *virtual*.  As in Modula-3, there are no shorthands
 
19
for referencing the object's members from its methods: the method function is
 
20
declared with an explicit first argument representing the object, which is
 
21
provided implicitly by the call.  As in Smalltalk, classes themselves are
 
22
objects.  This provides semantics for importing and renaming.  Unlike C++ and
 
23
Modula-3, built-in types can be used as base classes for extension by the user.
 
24
Also, like in C++, most built-in operators with special syntax (arithmetic
27
25
operators, subscripting etc.) can be redefined for class instances.
28
26
 
29
 
 
30
 
.. _tut-terminology:
31
 
 
32
 
A Word About Terminology
33
 
========================
34
 
 
35
 
Lacking universally accepted terminology to talk about classes, I will make
36
 
occasional use of Smalltalk and C++ terms.  (I would use Modula-3 terms, since
 
27
(Lacking universally accepted terminology to talk about classes, I will make
 
28
occasional use of Smalltalk and C++ terms.  I would use Modula-3 terms, since
37
29
its object-oriented semantics are closer to those of Python than C++, but I
38
30
expect that few readers have heard of it.)
39
31
 
 
32
 
 
33
.. _tut-object:
 
34
 
 
35
A Word About Names and Objects
 
36
==============================
 
37
 
40
38
Objects have individuality, and multiple names (in multiple scopes) can be bound
41
39
to the same object.  This is known as aliasing in other languages.  This is
42
40
usually not appreciated on a first glance at Python, and can be safely ignored
43
41
when dealing with immutable basic types (numbers, strings, tuples).  However,
44
 
aliasing has an (intended!) effect on the semantics of Python code involving
45
 
mutable objects such as lists, dictionaries, and most types representing
46
 
entities outside the program (files, windows, etc.).  This is usually used to
47
 
the benefit of the program, since aliases behave like pointers in some respects.
48
 
For example, passing an object is cheap since only a pointer is passed by the
49
 
implementation; and if a function modifies an object passed as an argument, the
50
 
caller will see the change --- this eliminates the need for two different
51
 
argument passing mechanisms as in Pascal.
 
42
aliasing has a possibly surprising effect on the semantics of Python code
 
43
involving mutable objects such as lists, dictionaries, and most other types.
 
44
This is usually used to the benefit of the program, since aliases behave like
 
45
pointers in some respects.  For example, passing an object is cheap since only a
 
46
pointer is passed by the implementation; and if a function modifies an object
 
47
passed as an argument, the caller will see the change --- this eliminates the
 
48
need for two different argument passing mechanisms as in Pascal.
52
49
 
53
50
 
54
51
.. _tut-scopes:
55
52
 
56
 
Python Scopes and Name Spaces
57
 
=============================
 
53
Python Scopes and Namespaces
 
54
============================
58
55
 
59
56
Before introducing classes, I first have to tell you something about Python's
60
57
scope rules.  Class definitions play some neat tricks with namespaces, and you
72
69
a function invocation.  In a sense the set of attributes of an object also form
73
70
a namespace.  The important thing to know about namespaces is that there is
74
71
absolutely no relation between names in different namespaces; for instance, two
75
 
different modules may both define a function "maximize" without confusion ---
 
72
different modules may both define a function ``maximize`` without confusion ---
76
73
users of the modules must prefix it with the module name.
77
74
 
78
75
By the way, I use the word *attribute* for any name following a dot --- for
89
86
:keyword:`del` statement.  For example, ``del modname.the_answer`` will remove
90
87
the attribute :attr:`the_answer` from the object named by ``modname``.
91
88
 
92
 
Name spaces are created at different moments and have different lifetimes.  The
 
89
Namespaces are created at different moments and have different lifetimes.  The
93
90
namespace containing the built-in names is created when the Python interpreter
94
91
starts up, and is never deleted.  The global namespace for a module is created
95
92
when the module definition is read in; normally, module namespaces also last
111
108
 
112
109
Although scopes are determined statically, they are used dynamically. At any
113
110
time during execution, there are at least three nested scopes whose namespaces
114
 
are directly accessible: the innermost scope, which is searched first, contains
115
 
the local names; the namespaces of any enclosing functions, which are searched
116
 
starting with the nearest enclosing scope; the middle scope, searched next,
117
 
contains the current module's global names; and the outermost scope (searched
118
 
last) is the namespace containing built-in names.
 
111
are 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
119
118
 
120
119
If a name is declared global, then all references and assignments go directly to
121
120
the middle scope containing the module's global names. Otherwise, all variables
136
135
time, so don't rely on dynamic name resolution!  (In fact, local variables are
137
136
already determined statically.)
138
137
 
139
 
A special quirk of Python is that -- if no :keyword:`global`
140
 
statement is in effect -- assignments to names always go
141
 
into the innermost scope.  Assignments do not copy data --- they just bind names
142
 
to objects.  The same is true for deletions: the statement ``del x`` removes the
143
 
binding of ``x`` from the namespace referenced by the local scope.  In fact, all
144
 
operations that introduce new names use the local scope: in particular, import
145
 
statements and function definitions bind the module or function name in the
146
 
local scope.  (The :keyword:`global` statement can be used to indicate that
147
 
particular variables live in the global scope.)
 
138
A special quirk of Python is that -- if no :keyword:`global` statement is in
 
139
effect -- assignments to names always go into the innermost scope.  Assignments
 
140
do not copy data --- they just bind names to objects.  The same is true for
 
141
deletions: the statement ``del x`` removes the binding of ``x`` from the
 
142
namespace referenced by the local scope.  In fact, all operations that introduce
 
143
new names use the local scope: in particular, :keyword:`import` statements and
 
144
function definitions bind the module or function name in the local scope.  (The
 
145
:keyword:`global` statement can be used to indicate that particular variables
 
146
live in the global scope.)
148
147
 
149
148
 
150
149
.. _tut-firstclasses:
332
331
attribute that is a function object, a method object is created by packing
333
332
(pointers to) the instance object and the function object just found together in
334
333
an abstract object: this is the method object.  When the method object is called
335
 
with an argument list, it is unpacked again, a new argument list is constructed
336
 
from the instance object and the original argument list, and the function object
337
 
is called with this new argument list.
 
334
with an argument list, a new argument list is constructed from the instance
 
335
object and the argument list, and the function object is called with this new
 
336
argument list.
338
337
 
339
338
 
340
339
.. _tut-remarks:
372
371
 
373
372
Often, the first argument of a method is called ``self``.  This is nothing more
374
373
than a convention: the name ``self`` has absolutely no special meaning to
375
 
Python.  (Note, however, that by not following the convention your code may be
 
374
Python.  Note, however, that by not following the convention your code may be
376
375
less readable to other Python programmers, and it is also conceivable that a
377
 
*class browser* program might be written that relies upon such a convention.)
 
376
*class browser* program might be written that relies upon such a convention.
378
377
 
379
378
Any function object that is a class attribute defines a method for instances of
380
379
that class.  It is not necessary that the function definition is textually
410
409
 
411
410
Methods may reference global names in the same way as ordinary functions.  The
412
411
global scope associated with a method is the module containing the class
413
 
definition.  (The class itself is never used as a global scope!)  While one
 
412
definition.  (The class itself is never used as a global scope.)  While one
414
413
rarely encounters a good reason for using global data in a method, there are
415
414
many legitimate uses of the global scope: for one thing, functions and modules
416
415
imported into the global scope can be used by methods, as well as functions and
417
416
classes defined in it.  Usually, the class containing the method is itself
418
417
defined in this global scope, and in the next section we'll find some good
419
 
reasons why a method would want to reference its own class!
 
418
reasons why a method would want to reference its own class.
420
419
 
421
420
Each value is an object, and therefore has a *class* (also called its *type*).
422
421
It is stored as ``object.__class__``.
467
466
simply replace the base class method of the same name. There is a simple way to
468
467
call the base class method directly: just call ``BaseClassName.methodname(self,
469
468
arguments)``.  This is occasionally useful to clients as well.  (Note that this
470
 
only works if the base class is defined or imported directly in the global
 
469
only works if the base class is accessible as ``BaseClassName`` in the global
471
470
scope.)
472
471
 
473
472
Python has two built-in functions that work with inheritance:
474
473
 
475
 
* Use :func:`isinstance` to check an object's type: ``isinstance(obj, int)``
 
474
* Use :func:`isinstance` to check an instance's type: ``isinstance(obj, int)``
476
475
  will be ``True`` only if ``obj.__class__`` is :class:`int` or some class
477
476
  derived from :class:`int`.
478
477
 
537
536
Private Variables
538
537
=================
539
538
 
540
 
There is limited support for class-private identifiers.  Any identifier of the
541
 
form ``__spam`` (at least two leading underscores, at most one trailing
542
 
underscore) is textually replaced with ``_classname__spam``, where ``classname``
543
 
is the current class name with leading underscore(s) stripped.  This mangling is
544
 
done without regard to the syntactic position of the identifier, so it can be
545
 
used to define class-private instance and class variables, methods, variables
546
 
stored in globals, and even variables stored in instances. private to this class
547
 
on instances of *other* classes.  Truncation may occur when the mangled name
548
 
would be longer than 255 characters. Outside classes, or when the class name
549
 
consists of only underscores, no mangling occurs.
550
 
 
551
 
Name mangling is intended to give classes an easy way to define "private"
552
 
instance variables and methods, without having to worry about instance variables
553
 
defined by derived classes, or mucking with instance variables by code outside
554
 
the class.  Note that the mangling rules are designed mostly to avoid accidents;
555
 
it still is possible for a determined soul to access or modify a variable that
556
 
is considered private.  This can even be useful in special circumstances, such
557
 
as in the debugger, and that's one reason why this loophole is not closed.
558
 
(Buglet: derivation of a class with the same name as the base class makes use of
559
 
private variables of the base class possible.)
 
539
"Private" instance variables that cannot be accessed except from inside an
 
540
object, don't exist in Python.  However, there is a convention that is followed
 
541
by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should
 
542
be treated as a non-public part of the API (whether it is a function, a method
 
543
or a data member).  It should be considered an implementation detail and subject
 
544
to change without notice.
 
545
 
 
546
Since there is a valid use-case for class-private members (namely to avoid name
 
547
clashes of names with names defined by subclasses), there is limited support for
 
548
such a mechanism, called :dfn:`name mangling`.  Any identifier of the form
 
549
``__spam`` (at least two leading underscores, at most one trailing underscore)
 
550
is textually replaced with ``_classname__spam``, where ``classname`` is the
 
551
current class name with leading underscore(s) stripped.  This mangling is done
 
552
without regard to the syntactic position of the identifier, as long as it
 
553
occurs within the definition of a class.
 
554
 
 
555
Note that the mangling rules are designed mostly to avoid accidents; it still is
 
556
possible to access or modify a variable that is considered private.  This can
 
557
even be useful in special circumstances, such as in the debugger.
560
558
 
561
559
Notice that code passed to ``exec``, ``eval()`` or ``execfile()`` does not
562
560
consider the classname of the invoking  class to be the current class; this is
609
607
User-defined exceptions are identified by classes as well.  Using this mechanism
610
608
it is possible to create extensible hierarchies of exceptions.
611
609
 
612
 
There are two new valid (semantic) forms for the raise statement::
 
610
There are two new valid (semantic) forms for the :keyword:`raise` statement::
613
611
 
614
612
   raise Class, instance
615
613
 
620
618
 
621
619
   raise instance.__class__, instance
622
620
 
623
 
A class in an except clause is compatible with an exception if it is the same
624
 
class or a base class thereof (but not the other way around --- an except clause
625
 
listing a derived class is not compatible with a base class).  For example, the
626
 
following code will print B, C, D in that order::
 
621
A class in an :keyword:`except` clause is compatible with an exception if it is
 
622
the same class or a base class thereof (but not the other way around --- an
 
623
except clause listing a derived class is not compatible with a base class).  For
 
624
example, the following code will print B, C, D in that order::
627
625
 
628
626
   class B:
629
627
       pass