This is /home/pdm/install/Python-2.1/Doc/tut/python-tut.info, produced
by makeinfo version 4.0 from tut.texi.

   April 15, 2001		2.1


File: python-tut.info,  Node: Inheritance,  Next: Private Variables,  Prev: Random Remarks,  Up: Classes

Inheritance
===========

   Of course, a language feature would not be worthy of the name "class"
without supporting inheritance.  The syntax for a derived class
definition looks as follows:

     class DerivedClassName(BaseClassName):
         <statement-1>
         .
         .
         .
         <statement-N>

   The name `BaseClassName' must be defined in a scope containing the
derived class definition.  Instead of a base class name, an expression
is also allowed.  This is useful when the base class is defined in
another module, e.g.,

     class DerivedClassName(modname.BaseClassName):

   Execution of a derived class definition proceeds the same as for a
base class.  When the class object is constructed, the base class is
remembered.  This is used for resolving attribute references: if a
requested attribute is not found in the class, it is searched in the
base class.  This rule is applied recursively if the base class itself
is derived from some other class.

   There's nothing special about instantiation of derived classes:
`DerivedClassName()' creates a new instance of the class.  Method
references are resolved as follows: the corresponding class attribute
is searched, descending down the chain of base classes if necessary,
and the method reference is valid if this yields a function object.

   Derived classes may override methods of their base classes.  Because
methods have no special privileges when calling other methods of the
same object, a method of a base class that calls another method defined
in the same base class, may in fact end up calling a method of a
derived class that overrides it.  (For C++ programmers: all methods in
Python are effectively `virtual'.)

   An overriding method in a derived class may in fact want to extend
rather than simply replace the base class method of the same name.
There is a simple way to call the base class method directly: just call
`BaseClassName.methodname(self, arguments)'.  This is occasionally
useful to clients as well.  (Note that this only works if the base
class is defined or imported directly in the global scope.)

* Menu:

* Multiple Inheritance::


File: python-tut.info,  Node: Multiple Inheritance,  Prev: Inheritance,  Up: Inheritance

Multiple Inheritance
--------------------

   Python supports a limited form of multiple inheritance as well.  A
class definition with multiple base classes looks as follows:

     class DerivedClassName(Base1, Base2, Base3):
         <statement-1>
         .
         .
         .
         <statement-N>

   The only rule necessary to explain the semantics is the resolution
rule used for class attribute references.  This is depth-first,
left-to-right.  Thus, if an attribute is not found in
`DerivedClassName', it is searched in `Base1', then (recursively) in
the base classes of `Base1', and only if it is not found there, it is
searched in `Base2', and so on.

   (To some people breadth first -- searching `Base2' and `Base3'
before the base classes of `Base1' -- looks more natural.  However,
this would require you to know whether a particular attribute of
`Base1' is actually defined in `Base1' or in one of its base classes
before you can figure out the consequences of a name conflict with an
attribute of `Base2'.  The depth-first rule makes no differences
between direct and inherited attributes of `Base1'.)

   It is clear that indiscriminate use of multiple inheritance is a
maintenance nightmare, given the reliance in Python on conventions to
avoid accidental name conflicts.  A well-known problem with multiple
inheritance is a class derived from two classes that happen to have a
common base class.  While it is easy enough to figure out what happens
in this case (the instance will have a single copy of "instance
variables" or data attributes used by the common base class), it is not
clear that these semantics are in any way useful.


File: python-tut.info,  Node: Private Variables,  Next: Odds and Ends,  Prev: Inheritance,  Up: Classes

Private Variables
=================

   There is limited support for class-private identifiers.  Any
identifier of the form `__spam' (at least two leading underscores, at
most one trailing underscore) is now textually replaced with
`_classname__spam', where `classname' is the current class name with
leading underscore(s) stripped.  This mangling is done without regard
of the syntactic position of the identifier, so it can be used to
define class-private instance and class variables, methods, as well as
globals, and even to store instance variables private to this class on
instances of _other_ classes.  Truncation may occur when the mangled
name would be longer than 255 characters.  Outside classes, or when the
class name consists of only underscores, no mangling occurs.

   Name mangling is intended to give classes an easy way to define
"private" instance variables and methods, without having to worry about
instance variables defined by derived classes, or mucking with instance
variables by code outside the class.  Note that the mangling rules are
designed mostly to avoid accidents; it still is possible for a
determined soul to access or modify a variable that is considered
private.  This can even be useful, e.g. for the debugger, and that's
one reason why this loophole is not closed.  (Buglet: derivation of a
class with the same name as the base class makes use of private
variables of the base class possible.)

   Notice that code passed to `exec', `eval()' or `evalfile()' does not
consider the classname of the invoking class to be the current class;
this is similar to the effect of the `global' statement, the effect of
which is likewise restricted to code that is byte-compiled together.
The same restriction applies to `getattr()', `setattr()' and
`delattr()', as well as when referencing `__dict__' directly.

   Here's an example of a class that implements its own `__getattr__()'
and `__setattr__()' methods and stores all attributes in a private
variable, in a way that works in all versions of Python, including
those available before this feature was added:

     class VirtualAttributes:
         __vdict = None
         __vdict_name = locals().keys()[0]
     
         def __init__(self):
             self.__dict__[self.__vdict_name] = {}
     
         def __getattr__(self, name):
             return self.__vdict[name]
     
         def __setattr__(self, name, value):
             self.__vdict[name] = value


File: python-tut.info,  Node: Odds and Ends,  Prev: Private Variables,  Up: Classes

Odds and Ends
=============

   Sometimes it is useful to have a data type similar to the Pascal
"record" or C "struct", bundling together a couple of named data items.
An empty class definition will do nicely, e.g.:

     class Employee:
         pass
     
     john = Employee() # Create an empty employee record
     
     # Fill the fields of the record
     john.name = 'John Doe'
     john.dept = 'computer lab'
     john.salary = 1000

   A piece of Python code that expects a particular abstract data type
can often be passed a class that emulates the methods of that data type
instead.  For instance, if you have a function that formats some data
from a file object, you can define a class with methods `read()' and
`readline()' that gets the data from a string buffer instead, and pass
it as an argument.

   Instance method objects have attributes, too: `m.im_self' is the
object of which the method is an instance, and `m.im_func' is the
function object corresponding to the method.

* Menu:

* Exceptions Can Be Classes::


File: python-tut.info,  Node: Exceptions Can Be Classes,  Prev: Odds and Ends,  Up: Odds and Ends

Exceptions Can Be Classes
-------------------------

   User-defined exceptions are no longer limited to being string objects
-- they can be identified by classes as well.  Using this mechanism it
is possible to create extensible hierarchies of exceptions.

   There are two new valid (semantic) forms for the raise statement:

     raise Class, instance
     
     raise instance

   In the first form, `instance' must be an instance of `Class' or of a
class derived from it.  The second form is a shorthand for:

     raise instance.__class__, instance

   An except clause may list classes as well as string objects.  A class
in an except clause is compatible with an exception if it is the same
class or a base class thereof (but not the other way around -- an
except clause listing a derived class is not compatible with a base
class).  For example, the following code will print B, C, D in that
order:

     class B:
         pass
     class C(B):
         pass
     class D(C):
         pass
     
     for c in [B, C, D]:
         try:
             raise c()
         except D:
             print "D"
         except C:
             print "C"
         except B:
             print "B"

   Note that if the except clauses were reversed (with `except B'
first), it would have printed B, B, B -- the first matching except
clause is triggered.

   When an error message is printed for an unhandled exception which is
a class, the class name is printed, then a colon and a space, and
finally the instance converted to a string using the built-in function
`str()'.


File: python-tut.info,  Node: What Now?,  Next: Interactive Input Editing and History Substitution,  Prev: Classes,  Up: Top

What Now?
*********

   Reading this tutorial has probably reinforced your interest in using
Python -- you should be eager to apply Python to solve your real-world
problems.  Now what should you do?

   You should read, or at least page through, the , which gives
complete (though terse) reference material about types, functions, and
modules that can save you a lot of time when writing Python programs.
The standard Python distribution includes a _lot_ of code in both C and
Python; there are modules to read UNIX mailboxes, retrieve documents
via HTTP, generate random numbers, parse command-line options, write
CGI programs, compress data, and a lot more; skimming through the
Library Reference will give you an idea of what's available.

   The major Python Web site is <http://www.python.org/>; it contains
code, documentation, and pointers to Python-related pages around the
Web.  This web site is mirrored in various places around the world,
such as Europe, Japan, and Australia; a mirror may be faster than the
main site, depending on your geographical location.  A more informal
site is <http://starship.python.net/>, which contains a bunch of
Python-related personal home pages; many people have downloadable
software there.

   For Python-related questions and problem reports, you can post to the
newsgroup `comp.lang.python', or send them to the mailing list at
<python-list@python.org>.  The newsgroup and mailing list are
gatewayed, so messages posted to one will automatically be forwarded to
the other.  There are around 120 postings a day, asking (and answering)
questions, suggesting new features, and announcing new modules.  Before
posting, be sure to check the list of Frequently Asked Questions (also
called the FAQ), at <http://www.python.org/doc/FAQ.html>, or look for
it in the `Misc/' directory of the Python source distribution.  Mailing
list archives are available at <http://www.python.org/pipermail/>.  The
FAQ answers many of the questions that come up again and again, and may
already contain the solution for your problem.


File: python-tut.info,  Node: Interactive Input Editing and History Substitution,  Next: Module Index,  Prev: What Now?,  Up: Top

Interactive Input Editing and History Substitution
**************************************************

   Some versions of the Python interpreter support editing of the
current input line and history substitution, similar to facilities
found in the Korn shell and the GNU Bash shell.  This is implemented
using the _GNU Readline_ library, which supports Emacs-style and
vi-style editing.  This library has its own documentation which I won't
duplicate here; however, the basics are easily explained.  The
interactive editing and history described here are optionally available
in the UNIX and CygWin versions of the interpreter.

   This chapter does _not_ document the editing facilities of Mark
Hammond's PythonWin package or the Tk-based environment, IDLE,
distributed with Python.  The command line history recall which
operates within DOS boxes on NT and some other DOS and Windows flavors
is yet another beast.

* Menu:

* Line Editing::
* History Substitution::
* Key Bindings::
* Commentary::


File: python-tut.info,  Node: Line Editing,  Next: History Substitution,  Prev: Interactive Input Editing and History Substitution,  Up: Interactive Input Editing and History Substitution

Line Editing
============

   If supported, input line editing is active whenever the interpreter
prints a primary or secondary prompt.  The current line can be edited
using the conventional Emacs control characters.  The most important of
these are: <C-A> (Control-A) moves the cursor to the beginning of the
line, <C-E> to the end, <C-B> moves it one position to the left, <C-F>
to the right.  Backspace erases the character to the left of the
cursor, <C-D> the character to its right.  <C-K> kills (erases) the
rest of the line to the right of the cursor, <C-Y> yanks back the last
killed string.  <C-underscore> undoes the last change you made; it can
be repeated for cumulative effect.


File: python-tut.info,  Node: History Substitution,  Next: Key Bindings,  Prev: Line Editing,  Up: Interactive Input Editing and History Substitution

History Substitution
====================

   History substitution works as follows.  All non-empty input lines
issued are saved in a history buffer, and when a new prompt is given
you are positioned on a new line at the bottom of this buffer.  <C-P>
moves one line up (back) in the history buffer, <C-N> moves one down.
Any line in the history buffer can be edited; an asterisk appears in
front of the prompt to mark a line as modified.  Pressing the <Return>
key passes the current line to the interpreter.  <C-R> starts an
incremental reverse search; <C-S> starts a forward search.


File: python-tut.info,  Node: Key Bindings,  Next: Commentary,  Prev: History Substitution,  Up: Interactive Input Editing and History Substitution

Key Bindings
============

   The key bindings and some other parameters of the Readline library
can be customized by placing commands in an initialization file called
`~{}/.inputrc'.  Key bindings have the form

     key-name: function-name

   or

     "string": function-name

   and options can be set with

     set option-name value

   For example:

     # I prefer vi-style editing:
     set editing-mode vi
     
     # Edit using a single line:
     set horizontal-scroll-mode On
     
     # Rebind some keys:
     Meta-h: backward-kill-word
     "\C-u": universal-argument
     "\C-x\C-r": re-read-init-file

   Note that the default binding for <Tab> in Python is to insert a
<Tab> character instead of Readline's default filename completion
function.  If you insist, you can override this by putting

     Tab: complete

   in your `~{}/.inputrc'.  (Of course, this makes it harder to type
indented continuation lines.)

   Automatic completion of variable and module names is optionally
available.  To enable it in the interpreter's interactive mode, add the
following to your startup file:(1)

     import rlcompleter, readline
     readline.parse_and_bind('tab: complete')

   This binds the TAB key to the completion function, so hitting the TAB
key twice suggests completions; it looks at Python statement names, the
current local variables, and the available module names.  For dotted
expressions such as `string.a', it will evaluate the the expression up
to the final `.' and then suggest completions from the attributes of
the resulting object.  Note that this may execute application-defined
code if an object with a `__getattr__()' method is part of the
expression.

   ---------- Footnotes ----------

   (1)  Python will execute the contents of a file identified by the
`PYTHONSTARTUP' environment variable when you start an interactive
interpreter.


File: python-tut.info,  Node: Commentary,  Prev: Key Bindings,  Up: Interactive Input Editing and History Substitution

Commentary
==========

   This facility is an enormous step forward compared to earlier
versions of the interpreter; however, some wishes are left: It would be
nice if the proper indentation were suggested on continuation lines (the
parser knows if an indent token is required next).  The completion
mechanism might use the interpreter's symbol table.  A command to check
(or even suggest) matching parentheses, quotes, etc., would also be
useful.


File: python-tut.info,  Node: Module Index,  Next: Class-Exception-Object Index,  Prev: Interactive Input Editing and History Substitution,  Up: Top

Module Index
************

* Menu:

* __builtin__:                           dir Function.
* compileall:                            Compiled Python files.
* pickle:                                pickle Module.
* readline:                              Key Bindings.
* rlcompleter:                           Key Bindings.
* string:                                Fancier Output Formatting.
* sys:                                   Standard Modules.


File: python-tut.info,  Node: Class-Exception-Object Index,  Next: Function-Method-Variable Index,  Prev: Module Index,  Up: Top

Class, Exception, and Object Index
**********************************

* Menu:

* file:                                  Reading and Writing Files.
* method:                                Instance Objects.


File: python-tut.info,  Node: Function-Method-Variable Index,  Next: Miscellaneous Index,  Prev: Class-Exception-Object Index,  Up: Top

Function, Method, and Variable Index
************************************

* Menu:

* open:                                  Reading and Writing Files.
* unicode:                               Unicode Strings.


File: python-tut.info,  Node: Miscellaneous Index,  Prev: Function-Method-Variable Index,  Up: Top

Miscellaneous Index
*******************

* Menu:

* docstrings <1>:                        Documentation Strings.
* docstrings:                            Defining Functions.
* documentation strings <1>:             Documentation Strings.
* documentation strings:                 Defining Functions.
* for:                                   for Statements.
* module search path:                    Module Search Path.
* strings, documentation <1>:            Documentation Strings.
* strings, documentation:                Defining Functions.


