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.
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.
32
A Word About Terminology
33
========================
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.)
35
A Word About Names and Objects
36
==============================
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.
56
Python Scopes and Name Spaces
57
=============================
53
Python Scopes and Namespaces
54
============================
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
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:
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
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.)
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.)
150
149
.. _tut-firstclasses:
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.
421
420
Each value is an object, and therefore has a *class* (also called its *type*).
422
421
It is stored as ``object.__class__``.
537
536
Private Variables
538
537
=================
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.
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.
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.
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.
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
621
619
raise instance.__class__, instance
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::