improve treatment of multi-line replies, ignore empty lines
[python/dscho.git] / Doc / ref3.tex
blob67848bb8b42b2831440aa3dd899d8e81f1c005b0
1 \chapter{Data model}
3 \section{Objects, values and types}
5 {\em Objects} are Python's abstraction for data. All data in a Python
6 program is represented by objects or by relations between objects.
7 (In a sense, and in conformance to Von Neumann's model of a
8 ``stored program computer'', code is also represented by objects.)
9 \index{object}
10 \index{data}
12 Every object has an identity, a type and a value. An object's {\em
13 identity} never changes once it has been created; you may think of it
14 as the object's address in memory. An object's {\em type} is also
15 unchangeable. It determines the operations that an object supports
16 (e.g. ``does it have a length?'') and also defines the possible
17 values for objects of that type. The {\em value} of some objects can
18 change. Objects whose value can change are said to be {\em mutable};
19 objects whose value is unchangeable once they are created are called
20 {\em immutable}. The type determines an object's (im)mutability.
21 \index{identity of an object}
22 \index{value of an object}
23 \index{type of an object}
24 \index{mutable object}
25 \index{immutable object}
27 Objects are never explicitly destroyed; however, when they become
28 unreachable they may be garbage-collected. An implementation is
29 allowed to delay garbage collection or omit it altogether --- it is a
30 matter of implementation quality how garbage collection is
31 implemented, as long as no objects are collected that are still
32 reachable. (Implementation note: the current implementation uses a
33 reference-counting scheme which collects most objects as soon as they
34 become unreachable, but never collects garbage containing circular
35 references.)
36 \index{garbage collection}
37 \index{reference counting}
38 \index{unreachable object}
40 Note that the use of the implementation's tracing or debugging
41 facilities may keep objects alive that would normally be collectable.
43 Some objects contain references to ``external'' resources such as open
44 files or windows. It is understood that these resources are freed
45 when the object is garbage-collected, but since garbage collection is
46 not guaranteed to happen, such objects also provide an explicit way to
47 release the external resource, usually a \verb@close@ method.
48 Programs are strongly recommended to always explicitly close such
49 objects.
51 Some objects contain references to other objects; these are called
52 {\em containers}. Examples of containers are tuples, lists and
53 dictionaries. The references are part of a container's value. In
54 most cases, when we talk about the value of a container, we imply the
55 values, not the identities of the contained objects; however, when we
56 talk about the (im)mutability of a container, only the identities of
57 the immediately contained objects are implied. (So, if an immutable
58 container contains a reference to a mutable object, its value changes
59 if that mutable object is changed.)
60 \index{container}
62 Types affect almost all aspects of objects' lives. Even the meaning
63 of object identity is affected in some sense: for immutable types,
64 operations that compute new values may actually return a reference to
65 any existing object with the same type and value, while for mutable
66 objects this is not allowed. E.g. after
68 \begin{verbatim}
69 a = 1; b = 1; c = []; d = []
70 \end{verbatim}
72 \verb@a@ and \verb@b@ may or may not refer to the same object with the
73 value one, depending on the implementation, but \verb@c@ and \verb@d@
74 are guaranteed to refer to two different, unique, newly created empty
75 lists.
77 \section{The standard type hierarchy} \label{types}
79 Below is a list of the types that are built into Python. Extension
80 modules written in C can define additional types. Future versions of
81 Python may add types to the type hierarchy (e.g. rational or complex
82 numbers, efficiently stored arrays of integers, etc.).
83 \index{type}
84 \indexii{data}{type}
85 \indexii{type}{hierarchy}
86 \indexii{extension}{module}
87 \index{C}
89 Some of the type descriptions below contain a paragraph listing
90 `special attributes'. These are attributes that provide access to the
91 implementation and are not intended for general use. Their definition
92 may change in the future. There are also some `generic' special
93 attributes, not listed with the individual objects: \verb@__methods__@
94 is a list of the method names of a built-in object, if it has any;
95 \verb@__members__@ is a list of the data attribute names of a built-in
96 object, if it has any.
97 \index{attribute}
98 \indexii{special}{attribute}
99 \indexiii{generic}{special}{attribute}
100 \ttindex{__methods__}
101 \ttindex{__members__}
103 \begin{description}
105 \item[None]
106 This type has a single value. There is a single object with this value.
107 This object is accessed through the built-in name \verb@None@.
108 It is returned from functions that don't explicitly return an object.
109 \ttindex{None}
110 \obindex{None@{\tt None}}
112 \item[Numbers]
113 These are created by numeric literals and returned as results by
114 arithmetic operators and arithmetic built-in functions. Numeric
115 objects are immutable; once created their value never changes. Python
116 numbers are of course strongly related to mathematical numbers, but
117 subject to the limitations of numerical representation in computers.
118 \obindex{number}
119 \obindex{numeric}
121 Python distinguishes between integers and floating point numbers:
123 \begin{description}
124 \item[Integers]
125 These represent elements from the mathematical set of whole numbers.
126 \obindex{integer}
128 There are two types of integers:
130 \begin{description}
132 \item[Plain integers]
133 These represent numbers in the range $-2^{31}$ through $2^{31}-1$.
134 (The range may be larger on machines with a larger natural word
135 size, but not smaller.)
136 When the result of an operation falls outside this range, the
137 exception \verb@OverflowError@ is raised.
138 For the purpose of shift and mask operations, integers are assumed to
139 have a binary, 2's complement notation using 32 or more bits, and
140 hiding no bits from the user (i.e., all $2^{32}$ different bit
141 patterns correspond to different values).
142 \obindex{plain integer}
144 \item[Long integers]
145 These represent numbers in an unlimited range, subject to available
146 (virtual) memory only. For the purpose of shift and mask operations,
147 a binary representation is assumed, and negative numbers are
148 represented in a variant of 2's complement which gives the illusion of
149 an infinite string of sign bits extending to the left.
150 \obindex{long integer}
152 \end{description} % Integers
154 The rules for integer representation are intended to give the most
155 meaningful interpretation of shift and mask operations involving
156 negative integers and the least surprises when switching between the
157 plain and long integer domains. For any operation except left shift,
158 if it yields a result in the plain integer domain without causing
159 overflow, it will yield the same result in the long integer domain or
160 when using mixed operands.
161 \indexii{integer}{representation}
163 \item[Floating point numbers]
164 These represent machine-level double precision floating point numbers.
165 You are at the mercy of the underlying machine architecture and
166 C implementation for the accepted range and handling of overflow.
167 \obindex{floating point}
168 \indexii{floating point}{number}
169 \index{C}
171 \end{description} % Numbers
173 \item[Sequences]
174 These represent finite ordered sets indexed by natural numbers.
175 The built-in function \verb@len()@ returns the number of elements
176 of a sequence. When this number is $n$, the index set contains
177 the numbers $0, 1, \ldots, n-1$. Element \verb@i@ of sequence
178 \verb@a@ is selected by \verb@a[i]@.
179 \obindex{seqence}
180 \bifuncindex{len}
181 \index{index operation}
182 \index{item selection}
183 \index{subscription}
185 Sequences also support slicing: \verb@a[i:j]@ selects all elements
186 with index $k$ such that $i <= k < j$. When used as an expression,
187 a slice is a sequence of the same type --- this implies that the
188 index set is renumbered so that it starts at 0 again.
189 \index{slicing}
191 Sequences are distinguished according to their mutability:
193 \begin{description}
195 \item[Immutable sequences]
196 An object of an immutable sequence type cannot change once it is
197 created. (If the object contains references to other objects,
198 these other objects may be mutable and may be changed; however
199 the collection of objects directly referenced by an immutable object
200 cannot change.)
201 \obindex{immutable sequence}
202 \obindex{immutable}
204 The following types are immutable sequences:
206 \begin{description}
208 \item[Strings]
209 The elements of a string are characters. There is no separate
210 character type; a character is represented by a string of one element.
211 Characters represent (at least) 8-bit bytes. The built-in
212 functions \verb@chr()@ and \verb@ord()@ convert between characters
213 and nonnegative integers representing the byte values.
214 Bytes with the values 0-127 represent the corresponding ASCII values.
215 The string data type is also used to represent arrays of bytes, e.g.
216 to hold data read from a file.
217 \obindex{string}
218 \index{character}
219 \index{byte}
220 \index{ASCII}
221 \bifuncindex{chr}
222 \bifuncindex{ord}
224 (On systems whose native character set is not ASCII, strings may use
225 EBCDIC in their internal representation, provided the functions
226 \verb@chr()@ and \verb@ord()@ implement a mapping between ASCII and
227 EBCDIC, and string comparison preserves the ASCII order.
228 Or perhaps someone can propose a better rule?)
229 \index{ASCII}
230 \index{EBCDIC}
231 \index{character set}
232 \indexii{string}{comparison}
233 \bifuncindex{chr}
234 \bifuncindex{ord}
236 \item[Tuples]
237 The elements of a tuple are arbitrary Python objects.
238 Tuples of two or more elements are formed by comma-separated lists
239 of expressions. A tuple of one element (a `singleton') can be formed
240 by affixing a comma to an expression (an expression by itself does
241 not create a tuple, since parentheses must be usable for grouping of
242 expressions). An empty tuple can be formed by enclosing `nothing' in
243 parentheses.
244 \obindex{tuple}
245 \indexii{singleton}{tuple}
246 \indexii{empty}{tuple}
248 \end{description} % Immutable sequences
250 \item[Mutable sequences]
251 Mutable sequences can be changed after they are created. The
252 subscription and slicing notations can be used as the target of
253 assignment and \verb@del@ (delete) statements.
254 \obindex{mutable sequece}
255 \obindex{mutable}
256 \indexii{assignment}{statement}
257 \index{delete}
258 \stindex{del}
259 \index{subscription}
260 \index{slicing}
262 There is currently a single mutable sequence type:
264 \begin{description}
266 \item[Lists]
267 The elements of a list are arbitrary Python objects. Lists are formed
268 by placing a comma-separated list of expressions in square brackets.
269 (Note that there are no special cases needed to form lists of length 0
270 or 1.)
271 \obindex{list}
273 \end{description} % Mutable sequences
275 \end{description} % Sequences
277 \item[Mapping types]
278 These represent finite sets of objects indexed by arbitrary index sets.
279 The subscript notation \verb@a[k]@ selects the element indexed
280 by \verb@k@ from the mapping \verb@a@; this can be used in
281 expressions and as the target of assignments or \verb@del@ statements.
282 The built-in function \verb@len()@ returns the number of elements
283 in a mapping.
284 \bifuncindex{len}
285 \index{subscription}
286 \obindex{mapping}
288 There is currently a single mapping type:
290 \begin{description}
292 \item[Dictionaries]
293 These represent finite sets of objects indexed by almost arbitrary
294 values. The only types of values not acceptable as keys are values
295 containing lists or dictionaries or other mutable types that are
296 compared by value rather than by object identity --- the reason being
297 that the implementation requires that a key's hash value be constant.
298 Numeric types used for keys obey the normal rules for numeric
299 comparison: if two numbers compare equal (e.g. 1 and 1.0) then they
300 can be used interchangeably to index the same dictionary entry.
302 Dictionaries are mutable; they are created by the \verb@{...}@
303 notation (see section \ref{dict}).
304 \obindex{dictionary}
305 \obindex{mutable}
307 \end{description} % Mapping types
309 \item[Callable types]
310 These are the types to which the function call (invocation) operation,
311 written as \verb@function(argument, argument, ...)@, can be applied:
312 \indexii{function}{call}
313 \index{invocation}
314 \indexii{function}{argument}
315 \obindex{callable}
317 \begin{description}
319 \item[User-defined functions]
320 A user-defined function object is created by a function definition
321 (see section \ref{function}). It should be called with an argument
322 list containing the same number of items as the function's formal
323 parameter list.
324 \indexii{user-defined}{function}
325 \obindex{function}
326 \obindex{user-defined function}
328 Special read-only attributes: \verb@func_code@ is the code object
329 representing the compiled function body, and \verb@func_globals@ is (a
330 reference to) the dictionary that holds the function's global
331 variables --- it implements the global name space of the module in
332 which the function was defined.
333 \ttindex{func_code}
334 \ttindex{func_globals}
335 \indexii{global}{name space}
337 \item[User-defined methods]
338 A user-defined method (a.k.a. {\em object closure}) is a pair of a
339 class instance object and a user-defined function. It should be
340 called with an argument list containing one item less than the number
341 of items in the function's formal parameter list. When called, the
342 class instance becomes the first argument, and the call arguments are
343 shifted one to the right.
344 \obindex{method}
345 \obindex{user-defined method}
346 \indexii{user-defined}{method}
347 \index{object closure}
349 Special read-only attributes: \verb@im_self@ is the class instance
350 object, \verb@im_func@ is the function object.
351 \ttindex{im_func}
352 \ttindex{im_self}
354 \item[Built-in functions]
355 A built-in function object is a wrapper around a C function. Examples
356 of built-in functions are \verb@len@ and \verb@math.sin@. There
357 are no special attributes. The number and type of the arguments are
358 determined by the C function.
359 \obindex{built-in function}
360 \obindex{function}
361 \index{C}
363 \item[Built-in methods]
364 This is really a different disguise of a built-in function, this time
365 containing an object passed to the C function as an implicit extra
366 argument. An example of a built-in method is \verb@list.append@ if
367 \verb@list@ is a list object.
368 \obindex{built-in method}
369 \obindex{method}
370 \indexii{built-in}{method}
372 \item[Classes]
373 Class objects are described below. When a class object is called as a
374 function, a new class instance (also described below) is created and
375 returned. This implies a call to the class's \verb@__init__@ method
376 if it has one. Any arguments are passed on to the \verb@__init__@
377 method -- if there is \verb@__init__@ method, the class must be called
378 without arguments.
379 \ttindex{__init__}
380 \obindex{class}
381 \obindex{class instance}
382 \obindex{instance}
383 \indexii{class object}{call}
385 \end{description}
387 \item[Modules]
388 Modules are imported by the \verb@import@ statement (see section
389 \ref{import}). A module object is a container for a module's name
390 space, which is a dictionary (the same dictionary as referenced by the
391 \verb@func_globals@ attribute of functions defined in the module).
392 Module attribute references are translated to lookups in this
393 dictionary. A module object does not contain the code object used to
394 initialize the module (since it isn't needed once the initialization
395 is done).
396 \stindex{import}
397 \obindex{module}
399 Attribute assignment update the module's name space dictionary.
401 Special read-only attributes: \verb@__dict__@ yields the module's name
402 space as a dictionary object; \verb@__name__@ yields the module's name
403 as a string object.
404 \ttindex{__dict__}
405 \ttindex{__name__}
406 \indexii{module}{name space}
408 \item[Classes]
409 Class objects are created by class definitions (see section
410 \ref{class}). A class is a container for a dictionary containing the
411 class's name space. Class attribute references are translated to
412 lookups in this dictionary. When an attribute name is not found
413 there, the attribute search continues in the base classes. The search
414 is depth-first, left-to-right in the order of their occurrence in the
415 base class list.
416 \obindex{class}
417 \obindex{class instance}
418 \obindex{instance}
419 \indexii{class object}{call}
420 \index{container}
421 \obindex{dictionary}
422 \indexii{class}{attribute}
424 Class attribute assignments update the class's dictionary, never the
425 dictionary of a base class.
426 \indexiii{class}{attribute}{assignment}
428 A class can be called as a function to yield a class instance (see
429 above).
430 \indexii{class object}{call}
432 Special read-only attributes: \verb@__dict__@ yields the dictionary
433 containing the class's name space; \verb@__bases__@ yields a tuple
434 (possibly empty or a singleton) containing the base classes, in the
435 order of their occurrence in the base class list.
436 \ttindex{__dict__}
437 \ttindex{__bases__}
439 \item[Class instances]
440 A class instance is created by calling a class object as a
441 function. A class instance has a dictionary in which
442 attribute references are searched. When an attribute is not found
443 there, and the instance's class has an attribute by that name, and
444 that class attribute is a user-defined function (and in no other
445 cases), the instance attribute reference yields a user-defined method
446 object (see above) constructed from the instance and the function.
447 \obindex{class instance}
448 \obindex{instance}
449 \indexii{class}{instance}
450 \indexii{class instance}{attribute}
452 Attribute assignments update the instance's dictionary.
453 \indexiii{class instance}{attribute}{assignment}
455 Class instances can pretend to be numbers, sequences, or mappings if
456 they have methods with certain special names. These are described in
457 section \ref{specialnames}.
458 \obindex{number}
459 \obindex{sequence}
460 \obindex{mapping}
462 Special read-only attributes: \verb@__dict__@ yields the attribute
463 dictionary; \verb@__class__@ yields the instance's class.
464 \ttindex{__dict__}
465 \ttindex{__class__}
467 \item[Files]
468 A file object represents an open file. (It is a wrapper around a C
469 {\tt stdio} file pointer.) File objects are created by the
470 \verb@open()@ built-in function, and also by \verb@posix.popen()@ and
471 the \verb@makefile@ method of socket objects. \verb@sys.stdin@,
472 \verb@sys.stdout@ and \verb@sys.stderr@ are file objects corresponding
473 to the interpreter's standard input, output and error streams.
474 See the Python Library Reference for methods of file objects and other
475 details.
476 \obindex{file}
477 \index{C}
478 \index{stdio}
479 \bifuncindex{open}
480 \bifuncindex{popen}
481 \bifuncindex{makefile}
482 \ttindex{stdin}
483 \ttindex{stdout}
484 \ttindex{stderr}
485 \ttindex{sys.stdin}
486 \ttindex{sys.stdout}
487 \ttindex{sys.stderr}
489 \item[Internal types]
490 A few types used internally by the interpreter are exposed to the user.
491 Their definition may change with future versions of the interpreter,
492 but they are mentioned here for completeness.
493 \index{internal type}
495 \begin{description}
497 \item[Code objects]
498 Code objects represent executable code. The difference between a code
499 object and a function object is that the function object contains an
500 explicit reference to the function's context (the module in which it
501 was defined) while a code object contains no context. There is no way
502 to execute a bare code object.
503 \obindex{code}
505 Special read-only attributes: \verb@co_code@ is a string representing
506 the sequence of instructions; \verb@co_consts@ is a list of literals
507 used by the code; \verb@co_names@ is a list of names (strings) used by
508 the code; \verb@co_filename@ is the filename from which the code was
509 compiled. (To find out the line numbers, you would have to decode the
510 instructions; the standard library module \verb@dis@ contains an
511 example of how to do this.)
512 \ttindex{co_code}
513 \ttindex{co_consts}
514 \ttindex{co_names}
515 \ttindex{co_filename}
517 \item[Frame objects]
518 Frame objects represent execution frames. They may occur in traceback
519 objects (see below).
520 \obindex{frame}
522 Special read-only attributes: \verb@f_back@ is to the previous
523 stack frame (towards the caller), or \verb@None@ if this is the bottom
524 stack frame; \verb@f_code@ is the code object being executed in this
525 frame; \verb@f_globals@ is the dictionary used to look up global
526 variables; \verb@f_locals@ is used for local variables;
527 \verb@f_lineno@ gives the line number and \verb@f_lasti@ gives the
528 precise instruction (this is an index into the instruction string of
529 the code object).
530 \ttindex{f_back}
531 \ttindex{f_code}
532 \ttindex{f_globals}
533 \ttindex{f_locals}
534 \ttindex{f_lineno}
535 \ttindex{f_lasti}
537 \item[Traceback objects] \label{traceback}
538 Traceback objects represent a stack trace of an exception. A
539 traceback object is created when an exception occurs. When the search
540 for an exception handler unwinds the execution stack, at each unwound
541 level a traceback object is inserted in front of the current
542 traceback. When an exception handler is entered
543 (see also section \ref{try}), the stack trace is
544 made available to the program as \verb@sys.exc_traceback@. When the
545 program contains no suitable handler, the stack trace is written
546 (nicely formatted) to the standard error stream; if the interpreter is
547 interactive, it is also made available to the user as
548 \verb@sys.last_traceback@.
549 \obindex{traceback}
550 \indexii{stack}{trace}
551 \indexii{exception}{handler}
552 \indexii{execution}{stack}
553 \ttindex{exc_traceback}
554 \ttindex{last_traceback}
555 \ttindex{sys.exc_traceback}
556 \ttindex{sys.last_traceback}
558 Special read-only attributes: \verb@tb_next@ is the next level in the
559 stack trace (towards the frame where the exception occurred), or
560 \verb@None@ if there is no next level; \verb@tb_frame@ points to the
561 execution frame of the current level; \verb@tb_lineno@ gives the line
562 number where the exception occurred; \verb@tb_lasti@ indicates the
563 precise instruction. The line number and last instruction in the
564 traceback may differ from the line number of its frame object if the
565 exception occurred in a \verb@try@ statement with no matching
566 \verb@except@ clause or with a \verb@finally@ clause.
567 \ttindex{tb_next}
568 \ttindex{tb_frame}
569 \ttindex{tb_lineno}
570 \ttindex{tb_lasti}
571 \stindex{try}
573 \end{description} % Internal types
575 \end{description} % Types
578 \section{Special method names} \label{specialnames}
580 A class can implement certain operations that are invoked by special
581 syntax (such as subscription or arithmetic operations) by defining
582 methods with special names. For instance, if a class defines a
583 method named \verb@__getitem__@, and \verb@x@ is an instance of this
584 class, then \verb@x[i]@ is equivalent to \verb@x.__getitem__(i)@.
585 (The reverse is not true --- if \verb@x@ is a list object,
586 \verb@x.__getitem__(i)@ is not equivalent to \verb@x[i]@.)
588 Except for \verb@__repr__@, \verb@__str__@ and \verb@__cmp__@,
589 attempts to execute an
590 operation raise an exception when no appropriate method is defined.
591 For \verb@__repr__@, the default is to return a string describing the
592 object's class and address.
593 For \verb@__cmp__@, the default is to compare instances based on their
594 address.
595 For \verb@__str__@, the default is to use \verb@__repr__@.
598 \subsection{Special methods for any type}
600 \begin{description}
602 \item[\tt __init__(self, args...)]
603 Called when the instance is created. The arguments are those passed
604 to the class constructor expression. If a base class has an
605 \code{__init__} method the derived class's \code{__init__} method must
606 explicitly call it to ensure proper initialization of the base class
607 part of the instance.
609 \item[\tt __del__(self)]
610 Called when the instance is about to be destroyed. If a base class
611 has an \code{__del__} method the derived class's \code{__del__} method
612 must explicitly call it to ensure proper deletion of the base class
613 part of the instance. Note that it is possible for the \code{__del__}
614 method to postpone destruction of the instance by creating a new
615 reference to it. It may then be called at a later time when this new
616 reference is deleted. It is not guaranteed that
617 \code{__del__} methods are called for objects that still exist when
618 the interpreter exits.
620 Note that \code{del x} doesn't directly call \code{x.__del__} -- the
621 former decrements the reference count for \code{x} by one, but
622 \code{x,__del__} is only called when its reference count reaches zero.
624 \item[\tt __repr__(self)]
625 Called by the \verb@repr()@ built-in function and by string conversions
626 (reverse or backward quotes) to compute the string representation of an object.
627 \indexii{string}{conversion}
628 \indexii{reverse}{quotes}
629 \indexii{backward}{quotes}
630 \index{back-quotes}
632 \item[\tt __str__(self)]
633 Called by the \verb@str()@ built-in function and by the \verb@print@
634 statement compute the string representation of an object.
636 \item[\tt __cmp__(self, other)]
637 Called by all comparison operations. Should return -1 if
638 \verb@self < other@, 0 if \verb@self == other@, +1 if
639 \verb@self > other@. If no \code{__cmp__} operation is defined, class
640 instances are compared by object identity (``address'').
641 (Implementation note: due to limitations in the interpreter,
642 exceptions raised by comparisons are ignored, and the objects will be
643 considered equal in this case.)
645 \item[\tt __hash__(self)]
646 Called for the key object for dictionary operations,
647 and by the built-in function
648 \code{hash()}. Should return a 32-bit integer usable as a hash value
649 for dictionary operations. The only required property is that objects
650 which compare equal have the same hash value; it is advised to somehow
651 mix together (e.g. using exclusing or) the hash values for the
652 components of the object that also play a part in comparison of
653 objects. If a class does not define a \code{__cmp__} method it should
654 not define a \code{__hash__} operation either; if it defines
655 \code{__cmp__} but not \code{__hash__} its instances will not be
656 usable as dictionary keys. If a class defines mutable objects and
657 implements a \code{__cmp__} method it should not implement
658 \code{__hash__}, since the dictionary implementation assumes that a
659 key's hash value is a constant.
660 \obindex{dictionary}
662 \item[\tt __call__(self, *args)]
663 Called when the instance is ``called'' as a function.
665 \end{description}
668 \subsection{Special methods for attribute access}
670 The following methods can be used to change the meaning of attribute
671 access for class instances.
673 \begin{description}
675 \item[\tt __getattr__(self, name)]
676 Called when an attribute lookup has not found the attribute in the
677 usual places (i.e. it is not an instance attribute nor is it found in
678 the class tree for \code{self}). \code{name} is the attribute name.
680 Note that if the attribute is found through the normal mechanism,
681 \code{__getattr__} is not called. (This is an asymmetry between
682 \code{__getattr__} and \code{__setattr__}.)
683 This is done both for efficiency reasons and because otherwise
684 \code{__getattr__} would have no way to access other attributes of the
685 instance.
686 Note that at least for instance variables, \code{__getattr__} can fake
687 total control by simply not inserting any values in the instance
688 attribute dictionary.
690 \item[\tt __setattr__(self, name, value)]
691 Called when an attribute assignment is attempted. This is called
692 instead of the normal mechanism (i.e. store the value as an instance
693 attribute). \code{name} is the attribute name, \code{value} is the
694 value to be assigned to it.
696 If \code{__setattr__} wants to assign to an instance attribute, it
697 should not simply execute \code{self.\var{name} = value} -- this would
698 cause a recursive call. Instead, it should insert the value in the
699 dictionary of instance attributes, e.g. \code{self.__dict__[name] =
700 value}.
702 \item[\tt __delattr__(self, name)]
703 Like \code{__setattr__} but for attribute deletion instead of
704 assignment.
706 \end{description}
709 \subsection{Special methods for sequence and mapping types}
711 \begin{description}
713 \item[\tt __len__(self)]
714 Called to implement the built-in function \verb@len()@. Should return
715 the length of the object, an integer \verb@>=@ 0. Also, an object
716 whose \verb@__len__()@ method returns 0 is considered to be false in a
717 Boolean context.
719 \item[\tt __getitem__(self, key)]
720 Called to implement evaluation of \verb@self[key]@. Note that the
721 special interpretation of negative keys (if the class wishes to
722 emulate a sequence type) is up to the \verb@__getitem__@ method.
724 \item[\tt __setitem__(self, key, value)]
725 Called to implement assignment to \verb@self[key]@. Same note as for
726 \verb@__getitem__@.
728 \item[\tt __delitem__(self, key)]
729 Called to implement deletion of \verb@self[key]@. Same note as for
730 \verb@__getitem__@.
732 \end{description}
735 \subsection{Special methods for sequence types}
737 \begin{description}
739 \item[\tt __getslice__(self, i, j)]
740 Called to implement evaluation of \verb@self[i:j]@. Note that missing
741 \verb@i@ or \verb@j@ are replaced by 0 or \verb@len(self)@,
742 respectively, and \verb@len(self)@ has been added (once) to originally
743 negative \verb@i@ or \verb@j@ by the time this function is called
744 (unlike for \verb@__getitem__@).
746 \item[\tt __setslice__(self, i, j, sequence)]
747 Called to implement assignment to \verb@self[i:j]@. Same notes as for
748 \verb@__getslice__@.
750 \item[\tt __delslice__(self, i, j)]
751 Called to implement deletion of \verb@self[i:j]@. Same notes as for
752 \verb@__getslice__@.
754 \end{description}
757 \subsection{Special methods for numeric types}
759 \begin{description}
761 \item[\tt __add__(self, other)]\itemjoin
762 \item[\tt __sub__(self, other)]\itemjoin
763 \item[\tt __mul__(self, other)]\itemjoin
764 \item[\tt __div__(self, other)]\itemjoin
765 \item[\tt __mod__(self, other)]\itemjoin
766 \item[\tt __divmod__(self, other)]\itemjoin
767 \item[\tt __pow__(self, other)]\itemjoin
768 \item[\tt __lshift__(self, other)]\itemjoin
769 \item[\tt __rshift__(self, other)]\itemjoin
770 \item[\tt __and__(self, other)]\itemjoin
771 \item[\tt __xor__(self, other)]\itemjoin
772 \item[\tt __or__(self, other)]\itembreak
773 Called to implement the binary arithmetic operations (\verb@+@,
774 \verb@-@, \verb@*@, \verb@/@, \verb@%@, \verb@divmod()@, \verb@pow()@,
775 \verb@<<@, \verb@>>@, \verb@&@, \verb@^@, \verb@|@).
777 \item[\tt __neg__(self)]\itemjoin
778 \item[\tt __pos__(self)]\itemjoin
779 \item[\tt __abs__(self)]\itemjoin
780 \item[\tt __invert__(self)]\itembreak
781 Called to implement the unary arithmetic operations (\verb@-@, \verb@+@,
782 \verb@abs()@ and \verb@~@).
784 \item[\tt __nonzero__(self)]
785 Called to implement boolean testing; should return 0 or 1. An
786 alternative name for this method is \verb@__len__@.
788 \item[\tt __coerce__(self, other)]
789 Called to implement ``mixed-mode'' numeric arithmetic. Should either
790 return a tuple containing self and other converted to a common numeric
791 type, or None if no way of conversion is known. When the common type
792 would be the type of other, it is sufficient to return None, since the
793 interpreter will also ask the other object to attempt a coercion (but
794 sometimes, if the implementation of the other type cannot be changed,
795 it is useful to do the conversion to the other type here).
797 Note that this method is not called to coerce the arguments to \verb@+@
798 and \verb@*@, because these are also used to implement sequence
799 concatenation and repetition, respectively. Also note that, for the
800 same reason, in \verb@n*x@, where \verb@n@ is a built-in number and
801 \verb@x@ is an instance, a call to \verb@x.__mul__(n)@ is made.%
802 \footnote{The interpreter should really distinguish between
803 user-defined classes implementing sequences, mappings or numbers, but
804 currently it doesn't --- hence this strange exception.}
806 \item[\tt __int__(self)]\itemjoin
807 \item[\tt __long__(self)]\itemjoin
808 \item[\tt __float__(self)]\itembreak
809 Called to implement the built-in functions \verb@int()@, \verb@long()@
810 and \verb@float()@. Should return a value of the appropriate type.
812 \item[\tt __oct__(self)]\itemjoin
813 \item[\tt __hex__(self)]\itembreak
814 Called to implement the built-in functions \verb@oct()@ and
815 \verb@hex()@. Should return a string value.
817 \end{description}