Inheritance

---
node61.html node51.html node59.html node1.html
---
# 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:
```text
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.,
```text
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 ``virtual functions''.)
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.)
---
- Multiple inheritance (node61.html#SECTION001051000000000000000)
---
node61.html node51.html node59.html node1.html
---
---
guido@cwi.nl


Multiple inheritance

---
node62.html node60.html node60.html node1.html
---
## Multiple inheritance
Python supports a limited form of multiple inheritance as well. A
class definition with multiple base classes looks as follows:
```text
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.
---
guido@cwi.nl


Odds and ends

---
node63.html node51.html node61.html node1.html
---
# 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.:
```text
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. (Unfortunately, this
technique has its limitations: a class can't define operations that
are accessed by special syntax such as sequence subscripting or
arithmetic operators, and assigning such a ``pseudo-file'' to
`sys.stdin` will not cause the interpreter to read further input
from it.)
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.
---
guido@cwi.nl


Recent Additions

---
node64.html tut.html node62.html node1.html
---
# Recent Additions
Python is an evolving language. Since this tutorial was last
thoroughly revised, several new features have been added to the
language. While ideally I should revise the tutorial to incorporate
them in the mainline of the text, lack of time currently requires me
to take a more modest approach. In this chapter I will briefly list the
most important improvements to the language and how you can use them
to your benefit.
---
- The Last Printed Expression (node64.html#SECTION001110000000000000000)
String Literals (node65.html#SECTION001120000000000000000)
- Double Quotes (node66.html#SECTION001121000000000000000)
Continuation Of String Literals (node67.html#SECTION001122000000000000000)
Triple-quoted strings (node68.html#SECTION001123000000000000000)
String Literal Juxtaposition (node69.html#SECTION001124000000000000000)
The Formatting Operator (node70.html#SECTION001130000000000000000)
- Basic Usage (node71.html#SECTION001131000000000000000)
Referencing Variables By Name (node72.html#SECTION001132000000000000000)
Optional Function Arguments (node73.html#SECTION001140000000000000000)
- Default Argument Values (node74.html#SECTION001141000000000000000)
Arbitrary Argument Lists (node75.html#SECTION001142000000000000000)
Lambda And Functional Programming Tools (node76.html#SECTION001150000000000000000)
- Lambda Forms (node77.html#SECTION001151000000000000000)
Map, Reduce and Filter (node78.html#SECTION001152000000000000000)
- Map. (node79.html#SECTION001152100000000000000)
Filter. (node80.html#SECTION001152200000000000000)
Reduce. (node81.html#SECTION001152300000000000000)
Continuation Lines Without Backslashes (node82.html#SECTION001160000000000000000)
Regular Expressions (node83.html#SECTION001170000000000000000)
Generalized Dictionaries (node84.html#SECTION001180000000000000000)
Miscellaneous New Built-in Functions (node85.html#SECTION001190000000000000000)
Else Clause For Try Statement (node86.html#SECTION0011100000000000000000)
New Class Features in Release 1.1 (node87.html#SECTION0011110000000000000000)
- New Operator Overloading (node88.html#SECTION0011111000000000000000)
Trapping Attribute Access (node89.html#SECTION0011112000000000000000)
Calling a Class Instance (node90.html#SECTION0011113000000000000000)
---
guido@cwi.nl


The Last Printed Expression

---
node65.html node63.html node63.html node1.html
---
# The Last Printed Expression
In interactive mode, the last printed expression is assigned to the
variable `_`. This means that when you are using Python as a
desk calculator, it is somewhat easier to continue calculations, for
example:
```text
>>> tax = 17.5 / 100
>>> price = 3.50
>>> price * tax
0.6125
>>> price + _
4.1125
>>> round(_, 2)
4.11
>>>
```
For reasons too embarrassing to explain, this variable is implemented
as a built-in (living in the module `__builtin__`), so it should
be treated as read-only by the user. I.e. don't explicitly assign a
value to it --- you would create an independent local variable with
the same name masking the built-in variable with its magic behavior.
---
guido@cwi.nl


String Literals

---
node66.html node63.html node64.html node1.html
---
# String Literals
---
- Double Quotes (node66.html#SECTION001121000000000000000)
Continuation Of String Literals (node67.html#SECTION001122000000000000000)
Triple-quoted strings (node68.html#SECTION001123000000000000000)
String Literal Juxtaposition (node69.html#SECTION001124000000000000000)
---
guido@cwi.nl


Double Quotes

---
node67.html node65.html node65.html node1.html
---
## Double Quotes
Python can now also use double quotes to surround string literals,
e.g. `"this doesn't hurt a bit"`. There is no semantic
difference between strings surrounded by single or double quotes.
---
guido@cwi.nl


Continuation Of String Literals

---
node68.html node65.html node66.html node1.html
---
## Continuation Of String Literals
String literals can span multiple lines by escaping newlines with
backslashes, e.g.
```text
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant.\n"
print hello
```
which would print the following:
```text
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
```
---
guido@cwi.nl


Triple-quoted strings

---
node69.html node65.html node67.html node1.html
---
## Triple-quoted strings
In some cases, when you need to include really long strings (e.g.
containing several paragraphs of informational text), it is annoying
that you have to terminate each line with `\n\`, especially if
you would like to reformat the text occasionally with a powerful text
editor like Emacs. For such situations, ``triple-quoted'' strings can
be used, e.g.
```text
hello = """

This string is bounded by triple double quotes (3 times ").
Unescaped newlines in the string are retained, though \
it is still possible\nto use all normal escape sequences.

Whitespace at the beginning of a line is
significant. If you need to include three opening quotes
you have to escape at least one of them, e.g. \""".

This string ends in a newline.
"""
```
Triple-quoted strings can be surrounded by three single quotes as
well, again without semantic difference.
---
guido@cwi.nl


String Literal Juxtaposition

---
node70.html node65.html node68.html node1.html
---
## String Literal Juxtaposition
One final twist: you can juxtapose multiple string literals. Two or
more adjacent string literals (but not arbitrary expressions!)
separated only by whitespace will be concatenated (without intervening
whitespace) into a single string object at compile time. This makes
it possible to continue a long string on the next line without
sacrificing indentation or performance, unlike the use of the string
concatenation operator `+` or the continuation of the literal
itself on the next line (since leading whitespace is significant
inside all types of string literals). Note that this feature, like
all string features except triple-quoted strings, is borrowed from
Standard C.
---
guido@cwi.nl


Interactive Mode

---
node8.html node5.html node6.html node1.html
---
## Interactive Mode
When commands are read from a tty, the interpreter is said to be in
interactive mode. In this mode it prompts for the next command
with the primary prompt, usually three greater-than signs (
>>>); for continuation lines it prompts with the secondary\
prompt, by default three dots (...). Typing an EOF (Control-D)
at the primary prompt causes the interpreter to exit with a zero exit
status.
The interpreter prints a welcome message stating its version number
and a copyright notice before printing the first prompt, e.g.:
```text
python
Python 1.2 (Mar 14 1995)
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
```
---
guido@cwi.nl


The Formatting Operator

---
node71.html node63.html node69.html node1.html
---
# The Formatting Operator
---
- Basic Usage (node71.html#SECTION001131000000000000000)
Referencing Variables By Name (node72.html#SECTION001132000000000000000)
---
guido@cwi.nl


Basic Usage

---
node72.html node70.html node70.html node1.html
---
## Basic Usage
The chapter on output formatting is really out of date: there is now
an almost complete interface to C-style printf formats. This is done
by overloading the modulo operator (`%`) for a left operand
which is a string, e.g.
```text
>>> import math
>>> print 'The value of PI is approximately %5.3f.' % math.pi
The value of PI is approximately 3.142.
>>>
```
If there is more than one format in the string you pass a tuple as
right operand, e.g.
```text
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> for name, phone in table.items():
... print '%-10s ==> %10d' % (name, phone)
...
Jack ==> 4098
Dcab ==> 8637678
Sjoerd ==> 4127
>>>
```
Most formats work exactly as in C and require that you pass the proper
type (however, if you don't you get an exception, not a core dump).
The `%s` format is more relaxed: if the corresponding argument is
not a string object, it is converted to string using the `str()`
built-in function. Using `*` to pass the width or precision in
as a separate (integer) argument is supported. The C formats
`%n` and `%p` are not supported.
---
guido@cwi.nl


Referencing Variables By Name

---
node73.html node70.html node71.html node1.html
---
## Referencing Variables By Name
If you have a really long format string that you don't want to split
up, it would be nice if you could reference the variables to be
formatted by name instead of by position. This can be done by using
an extension of C formats using the form `%(name)format`, e.g.
```text
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
>>>
```
This is particularly useful in combination with the new built-in
`vars()` function, which returns a dictionary containing all
local variables.
---
guido@cwi.nl


Optional Function Arguments

---
node74.html node63.html node72.html node1.html
---
# Optional Function Arguments
It is now possible to define functions with a variable number of
arguments. There are two forms, which can be combined.
---
- Default Argument Values (node74.html#SECTION001141000000000000000)
Arbitrary Argument Lists (node75.html#SECTION001142000000000000000)
---
guido@cwi.nl


Default Argument Values

---
node75.html node73.html node73.html node1.html
---
## Default Argument Values
The most useful form is to specify a default value for one or more
arguments. This creates a function that can be called with fewer
arguments than it is defined, e.g.
```text
def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please!'):
while 1:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return 1
if ok in ('n', 'no', 'nop', 'nope'): return 0
retries = retries - 1
if retries < 0: raise IOError, 'refusenik user'
print complaint
```
This function can be called either like this:
`ask_ok('Do you really want to quit?')` or like this:
`ask_ok('OK to overwrite the file?', 2)`.
The default values are evaluated at the point of function definition
in the defining scope, so that e.g.
```text
i = 5
def f(arg = i): print arg
i = 6
f()
```
will print `5`.
---
guido@cwi.nl


Arbitrary Argument Lists

---
node76.html node73.html node74.html node1.html
---
## Arbitrary Argument Lists
It is also possible to specify that a function can be called with an
arbitrary number of arguments. These arguments will be wrapped up in
a tuple. Before the variable number of arguments, zero or more normal
arguments may occur, e.g.
```text
def fprintf(file, format, *args):
file.write(format % args)
```
This feature may be combined with the previous, e.g.
```text
def but_is_it_useful(required, optional = None, *remains):
print "I don't know"
```
---
guido@cwi.nl


Lambda And Functional Programming Tools

---
node77.html node63.html node75.html node1.html
---
# Lambda And Functional Programming Tools
---
- Lambda Forms (node77.html#SECTION001151000000000000000)
Map, Reduce and Filter (node78.html#SECTION001152000000000000000)
- Map. (node79.html#SECTION001152100000000000000)
Filter. (node80.html#SECTION001152200000000000000)
Reduce. (node81.html#SECTION001152300000000000000)
---
guido@cwi.nl


Lambda Forms

---
node78.html node76.html node76.html node1.html
---
## Lambda Forms
By popular demand, a few features commonly found in functional
programming languages and Lisp have been added to Python. With the
`lambda` keyword, small anonymous functions can be created.
Here's a function that returns the sum of its two arguments:
`lambda a, b: a+b`. Lambda forms can be used wherever function
objects are required. They are syntactically restricted to a single
expression. Semantically, they are just syntactic sugar for a normal
function definition. Like nested function definitions, lambda forms
cannot reference variables from the containing scope, but this can be
overcome through the judicious use of default argument values, e.g.
```text
def make_incrementor(n):
return lambda x, incr=n: x+incr
```
---
guido@cwi.nl


Map, Reduce and Filter

---
node79.html node76.html node77.html node1.html
---
## Map, Reduce and Filter
Three new built-in functions on sequences are good candidate to pass
lambda forms.
---
- Map. (node79.html#SECTION001152100000000000000)
Filter. (node80.html#SECTION001152200000000000000)
Reduce. (node81.html#SECTION001152300000000000000)
---
guido@cwi.nl


Map.

---
node80.html node78.html node78.html node1.html
---
### Map.
`map(function, sequence)` calls `function(item)` for each of
the sequence's items and returns a list of the return values. For
example, to compute some cubes:
```text
>>> map(lambda x: x*x*x, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>>
```
More than one sequence may be passed; the function must then have as
many arguments as there are sequences and is called with the
corresponding item from each sequence (or `None` if some sequence
is shorter than another). If `None` is passed for the function,
a function returning its argument(s) is substituted.
Combining these two special cases, we see that
`map(None, list1, list2)` is a convenient way of turning a pair
of lists into a list of pairs. For example:
```text
>>> seq = range(8)
>>> map(None, seq, map(lambda x: x*x, seq))
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
>>>
```
---
guido@cwi.nl


The Interpreter and its Environment

---
node9.html node4.html node7.html node1.html
---
# The Interpreter and its Environment
---
- Error Handling (node9.html#SECTION00321000000000000000)
The Module Search Path (node10.html#SECTION00322000000000000000)
``Compiled'' Python files (node11.html#SECTION00323000000000000000)
Executable Python scripts (node12.html#SECTION00324000000000000000)
The Interactive Startup File (node13.html#SECTION00325000000000000000)
---
guido@cwi.nl


Filter.

---
node81.html node78.html node79.html node1.html
---
### Filter.
`filter(function, sequence)` returns a sequence (of the same
type, if possible) consisting of those items from the sequence for
which `function(item)` is true. For example, to compute some
primes:
```text
>>> filter(lambda x: x%2 != 0 and x%3 != 0, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>>
```
---
guido@cwi.nl


Reduce.

---
node82.html node78.html node80.html node1.html
---
### Reduce.
`reduce(function, sequence)` returns a single value constructed
by calling the (binary) function on the first two items of the
sequence, then on the result and the next item, and so on. For
example, to compute the sum of the numbers 1 through 10:
```text
>>> reduce(lambda x, y: x+y, range(1, 11))
55
>>>
```
If there's only one item in the sequence, its value is returned; if
the sequence is empty, an exception is raised.
A third argument can be passed to indicate the starting value. In this
case the starting value is returned for an empty sequence, and the
function is first applied to the starting value and the first sequence
item, then to the result and the next item, and so on. For example,
```text
>>> def sum(seq):
... return reduce(lambda x, y: x+y, seq, 0)
...
>>> sum(range(1, 11))
55
>>> sum([])
0
>>>
```
---
guido@cwi.nl


Continuation Lines Without Backslashes

---
node83.html node63.html node81.html node1.html
---
# Continuation Lines Without Backslashes
While the general mechanism for continuation of a source line on the
next physical line remains to place a backslash on the end of the
line, expressions inside matched parentheses (or square brackets, or
curly braces) can now also be continued without using a backslash.
This is particularly useful for calls to functions with many
arguments, and for initializations of large tables.
For example:
```text
month_names = ['Januari', 'Februari', 'Maart',
'April', 'Mei', 'Juni',
'Juli', 'Augustus', 'September',
'Oktober', 'November', 'December']
```
and
```text
CopyInternalHyperLinks(self.context.hyperlinks,
copy.context.hyperlinks,
uidremap)
```
---
guido@cwi.nl


Regular Expressions

---
node84.html node63.html node82.html node1.html
---
# Regular Expressions
While C's printf-style output formats, transformed into Python, are
adequate for most output formatting jobs, C's scanf-style input
formats are not very powerful. Instead of scanf-style input, Python
offers Emacs-style regular expressions as a powerful input and
scanning mechanism. Read the corresponding section in the Library
Reference for a full description.
---
guido@cwi.nl


Generalized Dictionaries

---
node85.html node63.html node83.html node1.html
---
# Generalized Dictionaries
The keys of dictionaries are no longer restricted to strings --- they
can be any immutable basic type including strings, numbers, tuples, or
(certain) class instances. (Lists and dictionaries are not acceptable
as dictionary keys, in order to avoid problems when the object used as
a key is modified.)
Dictionaries have two new methods: `d.values()` returns a list of
the dictionary's values, and `d.items()` returns a list of the
dictionary's (key, value) pairs. Like `d.keys()`, these
operations are slow for large dictionaries. Examples:
```text
>>> d = {100: 'honderd', 1000: 'duizend', 10: 'tien'}
>>> d.keys()
[100, 10, 1000]
>>> d.values()
['honderd', 'tien', 'duizend']
>>> d.items()
[(100, 'honderd'), (10, 'tien'), (1000, 'duizend')]
>>>
```
---
guido@cwi.nl


Miscellaneous New Built-in Functions

---
node86.html node63.html node84.html node1.html
---
# Miscellaneous New Built-in Functions
The function `vars()` returns a dictionary containing the current
local variables. With a module argument, it returns that module's
global variables. The old function `dir(x)` returns
`vars(x).keys()`.
The function `round(x)` returns a floating point number rounded
to the nearest integer (but still expressed as a floating point
number). E.g. `round(3.4) == 3.0` and `round(3.5) == 4.0`.
With a second argument it rounds to the specified number of digits,
e.g. `round(math.pi, 4) == 3.1416` or even
`round(123.4, -2) == 100.0`.
The function `hash(x)` returns a hash value for an object.
All object types acceptable as dictionary keys have a hash value (and
it is this hash value that the dictionary implementation uses).
The function `id(x)` return a unique identifier for an object.
For two objects x and y, `id(x) == id(y)` if and only if
`x is y`. (In fact the object's address is used.)
The function `hasattr(x, name)` returns whether an object has an
attribute with the given name (a string value). The function
`getattr(x, name)` returns the object's attribute with the given
name. The function `setattr(x, name, value)` assigns a value to
an object's attribute with the given name. These three functions are
useful if the attribute names are not known beforehand. Note that
`getattr(x, 'spam')` is equivalent to `x.spam`, and
`setattr(x, 'spam', y)` is equivalent to `x.spam = y`. By
definition, `hasattr(x, name)` returns true if and only if
`getattr(x, name)` returns without raising an exception.
---
guido@cwi.nl


Else Clause For Try Statement

---
node87.html node63.html node85.html node1.html
---
# Else Clause For Try Statement
The `try...except` statement now has an optional `else`
clause, which must follow all `except` clauses. It is useful to
place code that must be executed if the `try` clause does not
raise an exception. For example:
```text
for arg in sys.argv:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
```
---
guido@cwi.nl


New Class Features in Release 1.1

---
node88.html node63.html node86.html node1.html
---
# New Class Features in Release 1.1
Some changes have been made to classes: the operator overloading
mechanism is more flexible, providing more support for non-numeric use
of operators (including calling an object as if it were a function),
and it is possible to trap attribute accesses.
---
- New Operator Overloading (node88.html#SECTION0011111000000000000000)
Trapping Attribute Access (node89.html#SECTION0011112000000000000000)
Calling a Class Instance (node90.html#SECTION0011113000000000000000)
---
guido@cwi.nl


New Operator Overloading

---
node89.html node87.html node87.html node1.html
---
## New Operator Overloading
It is no longer necessary to coerce both sides of an operator to the
same class or type. A class may still provide a `__coerce__`
method, but this method may return objects of different types or
classes if it feels like it. If no `__coerce__` is defined, any
argument type or class is acceptable.
In order to make it possible to implement binary operators where the
right-hand side is a class instance but the left-hand side is not,
without using coercions, right-hand versions of all binary operators
may be defined. These have an `r' prepended to their name,
e.g. `__radd__`.
For example, here's a very simple class for representing times. Times
are initialized from a number of seconds (like time.time()). Times
are printed like this: `Wed Mar 15 12:28:48 1995`. Subtracting
two Times gives their difference in seconds. Adding or subtracting a
Time and a number gives a new Time. You can't add two times, nor can
you subtract a Time from a number.
```text
import time

class Time:
def __init__(self, seconds):
self.seconds = seconds
def __repr__(self):
return time.ctime(self.seconds)
def __add__(self, x):
return Time(self.seconds + x)
__radd__ = __add__ # support for x+t
def __sub__(self, x):
if hasattr(x, 'seconds'): # test if x could be a Time
return self.seconds - x.seconds
else:
return self.seconds - x

now = Time(time.time())
tomorrow = 24*3600 + now
yesterday = now - today
print tomorrow - yesterday # prints 172800
```
---
guido@cwi.nl


Trapping Attribute Access

---
node90.html node87.html node88.html node1.html
---
## Trapping Attribute Access
You can define three new ``magic'' methods in a class now:
`__getattr__(self, name)`, `__setattr__(self, name, value)`
and `__delattr__(self, name)`.
The `__getattr__` method is called when an attribute access fails,
i.e. when an attribute access would otherwise raise AttributeError ---
this is after the instance's dictionary and its class hierarchy
have been searched for the named attribute. Note that if this method
attempts to access any undefined instance attribute it will be called
recursively!
The `__setattr__` and `__delattr__` methods are called when
assignment to, respectively deletion of an attribute are attempted.
They are called instead of the normal action (which is to insert
or delete the attribute in the instance dictionary). If either of
these methods most set or delete any attribute, they can only do so by
using the instance dictionary directly --- `self.__dict__` --- else
they would be called recursively.
For example, here's a near-universal ``Wrapper'' class that passes all
its attribute accesses to another object. Note how the
`__init__` method inserts the wrapped object in
`self.__dict__` in order to avoid endless recursion
(`__setattr__` would call `__getattr__` which would call
itself recursively).
```text
class Wrapper:
def __init__(self, wrapped):
self.__dict__['wrapped'] = wrapped
def __getattr__(self, name):
return getattr(self.wrapped, name)
def __setattr__(self, name, value):
setattr(self.wrapped, name, value)
def __delattr__(self, name):
delattr(self.wrapped, name)

import sys
f = Wrapper(sys.stdout)
f.write('hello world\n') # prints 'hello world'
```
A simpler example of `__getattr__` is an attribute that is
computed each time (or the first time) it it accessed. For instance:
```text
from math import pi

class Circle:
def __init__(self, radius):
self.radius = radius
def __getattr__(self, name):
if name == 'circumference':
return 2 * pi * self.radius
if name == 'diameter':
return 2 * self.radius
if name == 'area':
return pi * pow(self.radius, 2)
raise AttributeError, name
```
---
guido@cwi.nl


Error Handling

---
node10.html node8.html node8.html node1.html
---
## Error Handling
When an error occurs, the interpreter prints an error
message and a stack trace. In interactive mode, it then returns to
the primary prompt; when input came from a file, it exits with a
nonzero exit status after printing
the stack trace. (Exceptions handled by an except clause in a
try statement are not errors in this context.) Some errors are
unconditionally fatal and cause an exit with a nonzero exit; this
applies to internal inconsistencies and some cases of running out of
memory. All error messages are written to the standard error stream;
normal output from the executed commands is written to standard
output.
Typing the interrupt character (usually Control-C or DEL) to the
primary or secondary prompt cancels the input and returns to the
primary prompt.
footnode.html#65
Typing an interrupt while a command is executing raises the
KeyboardInterrupt exception, which may be handled by a try
statement.
---
guido@cwi.nl


Calling a Class Instance

---
node91.html node87.html node89.html node1.html
---
## Calling a Class Instance
If a class defines a method `__call__` it is possible to call its
instances as if they were functions. For example:
```text
class PresetSomeArguments:
def __init__(self, func, *args):
self.func, self.args = func, args
def __call__(self, *args):
return apply(self.func, self.args + args)

f = PresetSomeArguments(pow, 2) # f(i) computes powers of 2
for i in range(10): print f(i), # prints 1 2 4 8 16 32 64 128 256 512
print # append newline
```
---
guido@cwi.nl


New in Release 1.2

---
node92.html tut.html node90.html node1.html
---
# New in Release 1.2
This chapter describes even more recent additions to the Python
language and library.
---
- New Class Features (node92.html#SECTION001210000000000000000)
Unix Signal Handling (node93.html#SECTION001220000000000000000)
Exceptions Can Be Classes (node94.html#SECTION001230000000000000000)
Object Persistency and Object Copying (node95.html#SECTION001240000000000000000)
- Persistent Objects (node96.html#SECTION001241000000000000000)
Copying Objects (node97.html#SECTION001242000000000000000)
Documentation Strings (node98.html#SECTION001250000000000000000)
Customizing Import and Built-Ins (node99.html#SECTION001260000000000000000)
Python and the World-Wide Web (node100.html#SECTION001270000000000000000)
Miscellaneous (node101.html#SECTION001280000000000000000)
---
guido@cwi.nl


New Class Features

---
node93.html node91.html node91.html node1.html
---
# New Class Features
The semantics of `__coerce__` have been changed to be more
reasonable. As an example, the new standard module `Complex`
implements fairly complete complex numbers using this. Additional
examples of classes with and without `__coerce__` methods can be
found in the `Demo/classes` subdirectory, modules `Rat` and
`Dates`.
If a class defines no `__coerce__` method, this is equivalent to
the following definition:
```text
def __coerce__(self, other): return self, other
```
If `__coerce__` coerces itself to an object of a different type,
the operation is carried out using that type --- in release 1.1, this
would cause an error.
Comparisons involving class instances now invoke `__coerce__`
exactly as if `cmp(x, y)` were a binary operator like `+`
(except if `x` and `y` are the same object).
---
guido@cwi.nl


Unix Signal Handling

---
node94.html node91.html node92.html node1.html
---
# Unix Signal Handling
On Unix, Python now supports signal handling. The module
`signal` exports functions `signal`, `pause` and
`alarm`, which act similar to their Unix counterparts. The
module also exports the conventional names for the various signal
classes (also usable with `os.kill()`) and `SIG_IGN` and
`SIG_DFL`. See the section on `signal` in the Library
Reference Manual for more information.
---
guido@cwi.nl


Exceptions Can Be Classes

---
node95.html node91.html node93.html node1.html
---
# 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:
```text
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
```text
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:
```text
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()`.
In this release, the built-in exceptions are still strings.
---
guido@cwi.nl


Object Persistency and Object Copying

---
node96.html node91.html node94.html node1.html
---
# Object Persistency and Object Copying
Two new modules, `pickle` and `shelve`, support storage and
retrieval of (almost) arbitrary Python objects on disk, using the
`dbm` package. A third module, `copy`, provides flexible
object copying operations. More information on these modules is
provided in the Library Reference Manual.
---
- Persistent Objects (node96.html#SECTION001241000000000000000)
Copying Objects (node97.html#SECTION001242000000000000000)
---
guido@cwi.nl


Persistent Objects

---
node97.html node95.html node95.html node1.html
---
## Persistent Objects
The module `pickle` provides a general framework for objects to
disassemble themselves into a stream of bytes and to reassemble such a
stream back into an object. It copes with reference sharing,
recursive objects and instances of user-defined classes, but not
(directly) with objects that have ``magical'' links into the operating
system such as open files, sockets or windows.
The `pickle` module defines a simple protocol whereby
user-defined classes can control how they are disassembled and
assembled. The method `__getinitargs__()`, if defined, returns
the argument list for the constructor to be used at assembly time (by
default the constructor is called without arguments). The methods
`__getstate__()` and `__setstate__()` are used to pass
additional state from disassembly to assembly; by default the
instance's `__dict__` is passed and restored.
Note that `pickle` does not open or close any files --- it can be
used equally well for moving objects around on a network or store them
in a database. For ease of debugging, and the inevitable occasional
manual patch-up, the constructed byte streams consist of printable
ASCII characters only (though it's not designed to be pretty).
The module `shelve` provides a simple model for storing objects
on files. The operation `shelve.open(filename)` returns a
``shelf'', which is a simple persistent database with a
dictionary-like interface. Database keys are strings, objects stored
in the database can be anything that `pickle` will handle.
---
guido@cwi.nl


Copying Objects

---
node98.html node95.html node96.html node1.html
---
## Copying Objects
The module `copy` exports two functions: `copy()` and
`deepcopy()`. The `copy()` function returns a ``shallow''
copy of an object; `deepcopy()` returns a ``deep'' copy. The
difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or
class instances):
- A shallow copy constructs a new compound object and then (to the
extent possible) inserts the same objects into in that the
original contains.
A deep copy constructs a new compound object and then, recursively,
inserts copies into it of the objects found in the original.
Both functions have the same restrictions and use the same protocols
as `pickle` --- user-defined classes can control how they are
copied by providing methods named `__getinitargs__()`,
`__getstate__()` and `__setstate__()`.
---
guido@cwi.nl


Documentation Strings

---
node99.html node91.html node97.html node1.html
---
# Documentation Strings
A variety of objects now have a new attribute, `__doc__`, which
is supposed to contain a documentation string (if no documentation is
present, the attribute is `None`). New syntax, compatible with
the old interpreter, allows for convenient initialization of the
`__doc__` attribute of modules, classes and functions by placing
a string literal by itself as the first statement in the suite. It
must be a literal --- an expression yielding a string object is not
accepted as a documentation string, since future tools may need to
derive documentation from source by parsing.
Here is a hypothetical, amply documented module called `Spam`:
```text
"""Spam operations.

This module exports two classes, a function and an exception:

class Spam: full Spam functionality --- three can sizes
class SpamLight: limited Spam functionality --- only one can size

def open(filename): open a file and return a corresponding Spam or
SpamLight object

GoneOff: exception raised for errors; should never happen

Note that it is always possible to convert a SpamLight object to a
Spam object by a simple method call, but that the reverse operation is
generally costly and may fail for a number of reasons.
"""

class SpamLight:
"""Limited spam functionality.

Supports a single can size, no flavor, and only hard disks.
"""

def __init__(self, size=12):
"""Construct a new SpamLight instance.

Argument is the can size.
"""
# etc.

# etc.

class Spam(SpamLight):
"""Full spam functionality.

Supports three can sizes, two flavor varieties, and all floppy
disk formats still supported by current hardware.
"""

def __init__(self, size1=8, size2=12, size3=20):
"""Construct a new Spam instance.

Arguments are up to three can sizes.
"""
# etc.

# etc.

def open(filename = "/dev/null"):
"""Open a can of Spam.

Argument must be an existing file.
"""
# etc.

class GoneOff:
"""Class used for Spam exceptions.

There shouldn't be any.
"""
pass
```
After executing ```import Spam`'', the following expressions
return the various documentation strings from the module:
```text
Spam.__doc__
Spam.SpamLight.__doc__
Spam.SpamLight.__init__.__doc__
Spam.Spam.__doc__
Spam.Spam.__init__.__doc__
Spam.open.__doc__
Spam.GoneOff.__doc__
```
There are emerging conventions about the content and formatting of
documentation strings.
The first line should always be a short, concise summary of the
object's purpose. For brevity, it should not explicitly state the
object's name or type, since these are available by other means
(except if the name happens to be a verb describing a function's
operation). This line should begin with a capital letter and end with
a period.
If there are more lines in the documentation string, the second line
should be blank, visually separating the summary from the rest of the
description. The following lines should be one of more of paragraphs
describing the objects calling conventions, its side effects, etc.
Some people like to copy the Emacs convention of using UPPER CASE for
function parameters --- this often saves a few words or lines.
The Python parser does not strip indentation from multi-line string
literals in Python, so tools that process documentation have to strip
indentation. This is done using the following convention. The first
non-blank line after the first line of the string determines the
amount of indentation for the entire documentation string. (We can't
use the first line since it is generally adjacent to the string's
opening quotes so its indentation is not apparent in the string
literal.) Whitespace ``equivalent'' to this indentation is then
stripped from the start of all lines of the string. Lines that are
indented less should not occur, but if they occur all their leading
whitespace should be stripped. Equivalence of whitespace should be
tested after expansion of tabs (to 8 spaces, normally).
In this release, few of the built-in or standard functions and modules
have documentation strings.
---
node99.html node91.html node97.html node1.html
---
---
guido@cwi.nl


Customizing Import and Built-Ins

---
node100.html node91.html node98.html node1.html
---
# Customizing Import and Built-Ins
In preparation for a ``restricted execution mode'' which will be
usable to run code received from an untrusted source (such as a WWW
server or client), the mechanism by which modules are imported has
been redesigned. It is now possible to provide your own function
`__import__` which is called whenever an `import` statement
is executed. There's a built-in function `__import__` which
provides the default implementation, but more interesting, the various
steps it takes are available separately from the new built-in module
`imp`. (See the section on `imp` in the Library Reference
Manual for more information on this module.)
When you do `dir()` in a fresh interactive interpreter you will
see another ``secret'' object that's present in every module:
`__builtins__`. This is either a dictionary or a module
containing the set of built-in objects used by functions defined in
current module. Although normally all modules are initialized with a
reference to the same dictionary, it is now possible to use a
different set of built-ins on a per-module basis. Together with the
fact that the `import` statement uses the `__import__`
function it finds in the importing modules' dictionary of built-ins,
this forms the basis for a future restricted execution mode.
---
guido@cwi.nl


Python Tutorial

---
node1.html node1.html
---
# Python Tutorial
Guido van Rossum
Dept. AA, CWI, P.O. Box 94079
1090 GB Amsterdam, The Netherlands
E-mail: guido@cwi.nl
10 April 1995
Release 1.2
Copyright © 1991-1995 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
### Abstract:
Python is a simple, yet powerful programming language that bridges the
gap between C and shell programming, and is thus ideally suited for
``throw-away programming''
and rapid prototyping. Its syntax is put
together from constructs borrowed from a variety of other languages;
most prominent are influences from ABC, C, Modula-3 and Icon.
The Python interpreter is easily extended with new functions and data
types implemented in C. Python is also suitable as an extension
language for highly customizable C applications such as editors or
window managers.
Python is available for various operating systems, amongst which
several flavors of Unix, Amoeba, the Apple Macintosh O.S.,
and MS-DOS.
This tutorial introduces the reader informally to the basic concepts
and features of the Python language and system. It helps to have a
Python interpreter handy for hands-on experience, but as the examples
are self-contained, the tutorial can be read off-line as well.
For a description of standard objects and modules, see the Python
Library Reference document. The Python Reference Manual gives
a more formal definition of the language.
---
- Contents (node1.html#SECTION00100000000000000000)
Whetting Your Appetite (node2.html#SECTION00200000000000000000)
- Where From Here (node3.html#SECTION00210000000000000000)
Using the Python Interpreter (node4.html#SECTION00300000000000000000)
- Invoking the Interpreter (node5.html#SECTION00310000000000000000)
- Argument Passing (node6.html#SECTION00311000000000000000)
Interactive Mode (node7.html#SECTION00312000000000000000)
The Interpreter and its Environment (node8.html#SECTION00320000000000000000)
- Error Handling (node9.html#SECTION00321000000000000000)
The Module Search Path (node10.html#SECTION00322000000000000000)
``Compiled'' Python files (node11.html#SECTION00323000000000000000)
Executable Python scripts (node12.html#SECTION00324000000000000000)
The Interactive Startup File (node13.html#SECTION00325000000000000000)
Interactive Input Editing and History Substitution (node14.html#SECTION00330000000000000000)
- Line Editing (node15.html#SECTION00331000000000000000)
History Substitution (node16.html#SECTION00332000000000000000)
Key Bindings (node17.html#SECTION00333000000000000000)
Commentary (node18.html#SECTION00334000000000000000)
An Informal Introduction to Python (node19.html#SECTION00400000000000000000)
- Using Python as a Calculator (node20.html#SECTION00410000000000000000)
- Numbers (node21.html#SECTION00411000000000000000)
Strings (node22.html#SECTION00412000000000000000)
Lists (node23.html#SECTION00413000000000000000)
First Steps Towards Programming (node24.html#SECTION00420000000000000000)
More Control Flow Tools (node25.html#SECTION00500000000000000000)
- If Statements (node26.html#SECTION00510000000000000000)
For Statements (node27.html#SECTION00520000000000000000)
The range() Function (node28.html#SECTION00530000000000000000)
Break and Continue Statements, and Else Clauses on Loops (node29.html#SECTION00540000000000000000)
Pass Statements (node30.html#SECTION00550000000000000000)
Defining Functions (node31.html#SECTION00560000000000000000)
Odds and Ends (node32.html#SECTION00600000000000000000)
- More on Lists (node33.html#SECTION00610000000000000000)
The del statement (node34.html#SECTION00620000000000000000)
Tuples and Sequences (node35.html#SECTION00630000000000000000)
Dictionaries (node36.html#SECTION00640000000000000000)
More on Conditions (node37.html#SECTION00650000000000000000)
Comparing Sequences and Other Types (node38.html#SECTION00660000000000000000)
Modules (node39.html#SECTION00700000000000000000)
- More on Modules (node40.html#SECTION00710000000000000000)
Standard Modules (node41.html#SECTION00720000000000000000)
The dir() function (node42.html#SECTION00730000000000000000)
Output Formatting (node43.html#SECTION00800000000000000000)
Errors and Exceptions (node44.html#SECTION00900000000000000000)
- Syntax Errors (node45.html#SECTION00910000000000000000)
Exceptions (node46.html#SECTION00920000000000000000)
Handling Exceptions (node47.html#SECTION00930000000000000000)
Raising Exceptions (node48.html#SECTION00940000000000000000)
User-defined Exceptions (node49.html#SECTION00950000000000000000)
Defining Clean-up Actions (node50.html#SECTION00960000000000000000)
Classes (node51.html#SECTION001000000000000000000)
- A word about terminology (node52.html#SECTION001010000000000000000)
Python scopes and name spaces (node53.html#SECTION001020000000000000000)
A first look at classes (node54.html#SECTION001030000000000000000)
- Class definition syntax (node55.html#SECTION001031000000000000000)
Class objects (node56.html#SECTION001032000000000000000)
Instance objects (node57.html#SECTION001033000000000000000)
Method objects (node58.html#SECTION001034000000000000000)
Random remarks (node59.html#SECTION001040000000000000000)
Inheritance (node60.html#SECTION001050000000000000000)
- Multiple inheritance (node61.html#SECTION001051000000000000000)
Odds and ends (node62.html#SECTION001060000000000000000)
Recent Additions (node63.html#SECTION001100000000000000000)
- The Last Printed Expression (node64.html#SECTION001110000000000000000)
String Literals (node65.html#SECTION001120000000000000000)
- Double Quotes (node66.html#SECTION001121000000000000000)
Continuation Of String Literals (node67.html#SECTION001122000000000000000)
Triple-quoted strings (node68.html#SECTION001123000000000000000)
String Literal Juxtaposition (node69.html#SECTION001124000000000000000)
The Formatting Operator (node70.html#SECTION001130000000000000000)
- Basic Usage (node71.html#SECTION001131000000000000000)
Referencing Variables By Name (node72.html#SECTION001132000000000000000)
Optional Function Arguments (node73.html#SECTION001140000000000000000)
- Default Argument Values (node74.html#SECTION001141000000000000000)
Arbitrary Argument Lists (node75.html#SECTION001142000000000000000)
Lambda And Functional Programming Tools (node76.html#SECTION001150000000000000000)
- Lambda Forms (node77.html#SECTION001151000000000000000)
Map, Reduce and Filter (node78.html#SECTION001152000000000000000)
- Map. (node79.html#SECTION001152100000000000000)
Filter. (node80.html#SECTION001152200000000000000)
Reduce. (node81.html#SECTION001152300000000000000)
Continuation Lines Without Backslashes (node82.html#SECTION001160000000000000000)
Regular Expressions (node83.html#SECTION001170000000000000000)
Generalized Dictionaries (node84.html#SECTION001180000000000000000)
Miscellaneous New Built-in Functions (node85.html#SECTION001190000000000000000)
Else Clause For Try Statement (node86.html#SECTION0011100000000000000000)
New Class Features in Release 1.1 (node87.html#SECTION0011110000000000000000)
- New Operator Overloading (node88.html#SECTION0011111000000000000000)
Trapping Attribute Access (node89.html#SECTION0011112000000000000000)
Calling a Class Instance (node90.html#SECTION0011113000000000000000)
New in Release 1.2 (node91.html#SECTION001200000000000000000)
- New Class Features (node92.html#SECTION001210000000000000000)
Unix Signal Handling (node93.html#SECTION001220000000000000000)
Exceptions Can Be Classes (node94.html#SECTION001230000000000000000)
Object Persistency and Object Copying (node95.html#SECTION001240000000000000000)
- Persistent Objects (node96.html#SECTION001241000000000000000)
Copying Objects (node97.html#SECTION001242000000000000000)
Documentation Strings (node98.html#SECTION001250000000000000000)
Customizing Import and Built-Ins (node99.html#SECTION001260000000000000000)
Python and the World-Wide Web (node100.html#SECTION001270000000000000000)
Miscellaneous (node101.html#SECTION001280000000000000000)
About this document ... (node102.html#SECTION001300000000000000000)
---
node1.html node1.html
---
---
guido@cwi.nl