cinap_lenrekadd hg and python4bb9e2215 years agoHistory
2225 lines · 96.3 KB · TeX
RawDownload
\chapter{Data model\label{datamodel}}  \section{Objects, values and types\label{objects}} \dfn{Objects} are Python's abstraction for data.  All data in a Pythonprogram is represented by objects or by relations between objects.(In a sense, and in conformance to Von Neumann's model of a``stored program computer,'' code is also represented by objects.)\index{object}\index{data} Every object has an identity, a type and a value.  An object's\emph{identity} never changes once it has been created; you may thinkof it as the object's address in memory.  The `\keyword{is}' operatorcompares the identity of two objects; the\function{id()}\bifuncindex{id} function returns an integerrepresenting its identity (currently implemented as its address).An object's \dfn{type} isalso unchangeable.\footnote{Since Python 2.2, a gradual merging oftypes and classes has been started that makes this and a few otherassertions made in this manual not 100\% accurate and complete:for example, it \emph{is} now possible in some cases to change anobject's type, under certain controlled conditions.  Until this manualundergoes extensive revision, it must now be taken as authoritativeonly regarding ``classic classes'', that are still the default, forcompatibility purposes, in Python 2.2 and 2.3.  For more information,see \url{http://www.python.org/doc/newstyle.html}.}An object's type determines the operations that the objectsupports (e.g., ``does it have a length?'') and also defines thepossible values for objects of that type.  The\function{type()}\bifuncindex{type} function returns an object's type(which is an object itself).  The \emph{value} of someobjects can change.  Objects whose value can change are said to be\emph{mutable}; objects whose value is unchangeable once they arecreated are called \emph{immutable}.(The value of an immutable container object that contains a referenceto a mutable object can change when the latter's value is changed;however the container is still considered immutable, because thecollection of objects it contains cannot be changed.  So, immutabilityis not strictly the same as having an unchangeable value, it is moresubtle.)An object's mutability is determined by its type; for instance,numbers, strings and tuples are immutable, while dictionaries andlists are mutable.\index{identity of an object}\index{value of an object}\index{type of an object}\index{mutable object}\index{immutable object} Objects are never explicitly destroyed; however, when they becomeunreachable they may be garbage-collected.  An implementation isallowed to postpone garbage collection or omit it altogether --- it isa matter of implementation quality how garbage collection isimplemented, as long as no objects are collected that are stillreachable.  (Implementation note: the current implementation uses areference-counting scheme with (optional) delayed detection ofcyclically linked garbage, which collects most objects as soon as theybecome unreachable, but is not guaranteed to collect garbagecontaining circular references.  See the\citetitle[../lib/module-gc.html]{Python Library Reference} forinformation on controlling the collection of cyclic garbage.)\index{garbage collection}\index{reference counting}\index{unreachable object} Note that the use of the implementation's tracing or debuggingfacilities may keep objects alive that would normally be collectable.Also note that catching an exception with a`\keyword{try}...\keyword{except}' statement may keep objects alive. Some objects contain references to ``external'' resources such as openfiles or windows.  It is understood that these resources are freedwhen the object is garbage-collected, but since garbage collection isnot guaranteed to happen, such objects also provide an explicit way torelease the external resource, usually a \method{close()} method.Programs are strongly recommended to explicitly close suchobjects.  The `\keyword{try}...\keyword{finally}' statement providesa convenient way to do this. Some objects contain references to other objects; these are called\emph{containers}.  Examples of containers are tuples, lists anddictionaries.  The references are part of a container's value.  Inmost cases, when we talk about the value of a container, we imply thevalues, not the identities of the contained objects; however, when wetalk about the mutability of a container, only the identities ofthe immediately contained objects are implied.  So, if an immutablecontainer (like a tuple)contains a reference to a mutable object, its value changesif that mutable object is changed.\index{container} Types affect almost all aspects of object behavior.  Even the importanceof object identity is affected in some sense: for immutable types,operations that compute new values may actually return a reference toany existing object with the same type and value, while for mutableobjects this is not allowed.  E.g., after\samp{a = 1; b = 1},\code{a} and \code{b} may or may not refer to the same object with thevalue one, depending on the implementation, but after\samp{c = []; d = []}, \code{c} and \code{d}are guaranteed to refer to two different, unique, newly created emptylists.(Note that \samp{c = d = []} assigns the same object to both\code{c} and \code{d}.)  \section{The standard type hierarchy\label{types}} Below is a list of the types that are built into Python.  Extensionmodules (written in C, Java, or other languages, depending onthe implementation) can define additional types.  Future versions ofPython may add types to the type hierarchy (e.g., rationalnumbers, efficiently stored arrays of integers, etc.).\index{type}\indexii{data}{type}\indexii{type}{hierarchy}\indexii{extension}{module}\indexii{C}{language} Some of the type descriptions below contain a paragraph listing`special attributes.'  These are attributes that provide access to theimplementation and are not intended for general use.  Their definitionmay change in the future.\index{attribute}\indexii{special}{attribute}\indexiii{generic}{special}{attribute} \begin{description} \item[None]This type has a single value.  There is a single object with this value.This object is accessed through the built-in name \code{None}.It is used to signify the absence of a value in many situations, e.g.,it is returned from functions that don't explicitly return anything.Its truth value is false.\obindex{None} \item[NotImplemented]This type has a single value.  There is a single object with this value.This object is accessed through the built-in name \code{NotImplemented}.Numeric methods and rich comparison methods may return this value ifthey do not implement the operation for the operands provided.  (Theinterpreter will then try the reflected operation, or some otherfallback, depending on the operator.)  Its truth value is true.\obindex{NotImplemented} \item[Ellipsis]This type has a single value.  There is a single object with this value.This object is accessed through the built-in name \code{Ellipsis}.It is used to indicate the presence of the \samp{...} syntax in aslice.  Its truth value is true.\obindex{Ellipsis} \item[Numbers]These are created by numeric literals and returned as results byarithmetic operators and arithmetic built-in functions.  Numericobjects are immutable; once created their value never changes.  Pythonnumbers are of course strongly related to mathematical numbers, butsubject to the limitations of numerical representation in computers.\obindex{numeric} Python distinguishes between integers, floating point numbers, andcomplex numbers: \begin{description}\item[Integers]These represent elements from the mathematical set of integers(positive and negative).\obindex{integer} There are three types of integers: \begin{description} \item[Plain integers]These represent numbers in the range -2147483648 through 2147483647.(The range may be larger on machines with a larger natural wordsize, but not smaller.)When the result of an operation would fall outside this range, theresult is normally returned as a long integer (in some cases, theexception \exception{OverflowError} is raised instead).For the purpose of shift and mask operations, integers are assumed tohave a binary, 2's complement notation using 32 or more bits, andhiding no bits from the user (i.e., all 4294967296 different bitpatterns correspond to different values).\obindex{plain integer}\withsubitem{(built-in exception)}{\ttindex{OverflowError}} \item[Long integers]These represent numbers in an unlimited range, subject to available(virtual) memory only.  For the purpose of shift and mask operations,a binary representation is assumed, and negative numbers arerepresented in a variant of 2's complement which gives the illusion ofan infinite string of sign bits extending to the left.\obindex{long integer} \item[Booleans]These represent the truth values False and True.  The two objectsrepresenting the values False and True are the only Boolean objects.The Boolean type is a subtype of plain integers, and Boolean valuesbehave like the values 0 and 1, respectively, in almost all contexts,the exception being that when converted to a string, the strings\code{"False"} or \code{"True"} are returned, respectively.\obindex{Boolean}\ttindex{False}\ttindex{True} \end{description} % Integers The rules for integer representation are intended to give the mostmeaningful interpretation of shift and mask operations involvingnegative integers and the least surprises when switching between theplain and long integer domains.  Any operation except left shift,if it yields a result in the plain integer domain without causingoverflow, will yield the same result in the long integer domain orwhen using mixed operands.\indexii{integer}{representation} \item[Floating point numbers]These represent machine-level double precision floating point numbers.  You are at the mercy of the underlying machine architecture (andC or Java implementation) for the accepted range and handling of overflow.Python does not support single-precision floating point numbers; thesavings in processor and memory usage that are usually the reason for usingthese is dwarfed by the overhead of using objects in Python, so thereis no reason to complicate the language with two kinds of floatingpoint numbers.\obindex{floating point}\indexii{floating point}{number}\indexii{C}{language}\indexii{Java}{language} \item[Complex numbers]These represent complex numbers as a pair of machine-level doubleprecision floating point numbers.  The same caveats apply as forfloating point numbers.  The real and imaginary parts of a complexnumber \code{z} can be retrieved through the read-only attributes\code{z.real} and \code{z.imag}.\obindex{complex}\indexii{complex}{number} \end{description} % Numbers  \item[Sequences]These represent finite ordered sets indexed by non-negative numbers.The built-in function \function{len()}\bifuncindex{len} returns thenumber of items of a sequence.When the length of a sequence is \var{n}, theindex set contains the numbers 0, 1, \ldots, \var{n}-1.  Item\var{i} of sequence \var{a} is selected by \code{\var{a}[\var{i}]}.\obindex{sequence}\index{index operation}\index{item selection}\index{subscription} Sequences also support slicing: \code{\var{a}[\var{i}:\var{j}]}selects all items with index \var{k} such that \var{i} \code{<=}\var{k} \code{<} \var{j}.  When used as an expression, a slice is asequence of the same type.  This implies that the index set isrenumbered so that it starts at 0.\index{slicing} Some sequences also support ``extended slicing'' with a third ``step''parameter: \code{\var{a}[\var{i}:\var{j}:\var{k}]} selects all itemsof \var{a} with index \var{x} where \code{\var{x} = \var{i} +\var{n}*\var{k}}, \var{n} \code{>=} \code{0} and \var{i} \code{<=}\var{x} \code{<} \var{j}.\index{extended slicing} Sequences are distinguished according to their mutability: \begin{description} \item[Immutable sequences]An object of an immutable sequence type cannot change once it iscreated.  (If the object contains references to other objects,these other objects may be mutable and may be changed; however,the collection of objects directly referenced by an immutable objectcannot change.)\obindex{immutable sequence}\obindex{immutable} The following types are immutable sequences: \begin{description} \item[Strings]The items of a string are characters.  There is no separatecharacter type; a character is represented by a string of one item.Characters represent (at least) 8-bit bytes.  The built-infunctions \function{chr()}\bifuncindex{chr} and\function{ord()}\bifuncindex{ord} convert between characters andnonnegative integers representing the byte values.  Bytes with thevalues 0-127 usually represent the corresponding \ASCII{} values, butthe interpretation of values is up to the program.  The stringdata type is also used to represent arrays of bytes, e.g., to hold dataread from a file.\obindex{string}\index{character}\index{byte}\index{ASCII@\ASCII} (On systems whose native character set is not \ASCII, strings may useEBCDIC in their internal representation, provided the functions\function{chr()} and \function{ord()} implement a mapping between \ASCII{} andEBCDIC, and string comparison preserves the \ASCII{} order.Or perhaps someone can propose a better rule?)\index{ASCII@\ASCII}\index{EBCDIC}\index{character set}\indexii{string}{comparison}\bifuncindex{chr}\bifuncindex{ord} \item[Unicode]The items of a Unicode object are Unicode code units.  A Unicode codeunit is represented by a Unicode object of one item and can holdeither a 16-bit or 32-bit value representing a Unicode ordinal (themaximum value for the ordinal is given in \code{sys.maxunicode}, anddepends on how Python is configured at compile time).  Surrogate pairsmay be present in the Unicode object, and will be reported as twoseparate items.  The built-in functions\function{unichr()}\bifuncindex{unichr} and\function{ord()}\bifuncindex{ord} convert between code units andnonnegative integers representing the Unicode ordinals as defined inthe Unicode Standard 3.0. Conversion from and to other encodings arepossible through the Unicode method \method{encode()} and the built-infunction \function{unicode()}.\bifuncindex{unicode}\obindex{unicode}\index{character}\index{integer}\index{Unicode} \item[Tuples]The items of a tuple are arbitrary Python objects.Tuples of two or more items are formed by comma-separated listsof expressions.  A tuple of one item (a `singleton') can be formedby affixing a comma to an expression (an expression by itself doesnot create a tuple, since parentheses must be usable for grouping ofexpressions).  An empty tuple can be formed by an empty pair ofparentheses.\obindex{tuple}\indexii{singleton}{tuple}\indexii{empty}{tuple} \end{description} % Immutable sequences \item[Mutable sequences]Mutable sequences can be changed after they are created.  Thesubscription and slicing notations can be used as the target ofassignment and \keyword{del} (delete) statements.\obindex{mutable sequence}\obindex{mutable}\indexii{assignment}{statement}\index{delete}\stindex{del}\index{subscription}\index{slicing} There is currently a single intrinsic mutable sequence type: \begin{description} \item[Lists]The items of a list are arbitrary Python objects.  Lists are formedby placing a comma-separated list of expressions in square brackets.(Note that there are no special cases needed to form lists of length 0or 1.)\obindex{list} \end{description} % Mutable sequences The extension module \module{array}\refstmodindex{array} provides anadditional example of a mutable sequence type.  \end{description} % Sequences  \item[Set types]These represent unordered, finite sets of unique, immutable objects.As such, they cannot be indexed by any subscript. However, they can beiterated over, and the built-in function \function{len()} returns thenumber of items in a set. Common uses for sets arefast membership testing, removing duplicates from a sequence, andcomputing mathematical operations such as intersection, union, difference,and symmetric difference.\bifuncindex{len}\obindex{set type} For set elements, the same immutability rules apply as for dictionarykeys. Note that numeric types obey the normal rules for numericcomparison: if two numbers compare equal (e.g., \code{1} and\code{1.0}), only one of them can be contained in a set. There are currently two intrinsic set types: \begin{description} \item[Sets]These\obindex{set} represent a mutable set. They are created by thebuilt-in \function{set()} constructor and can be modified afterwardsby several methods, such as \method{add()}. \item[Frozen sets]These\obindex{frozenset} represent an immutable set. They are created bythe built-in \function{frozenset()} constructor. As a frozenset isimmutable and hashable, it can be used again as an element of another set,or as a dictionary key. \end{description} % Set types  \item[Mappings]These represent finite sets of objects indexed by arbitrary index sets.The subscript notation \code{a[k]} selects the item indexedby \code{k} from the mapping \code{a}; this can be used inexpressions and as the target of assignments or \keyword{del} statements.The built-in function \function{len()} returns the number of itemsin a mapping.\bifuncindex{len}\index{subscription}\obindex{mapping} There is currently a single intrinsic mapping type: \begin{description} \item[Dictionaries]These\obindex{dictionary} represent finite sets of objects indexed bynearly arbitrary values.  The only types of values not acceptable askeys are values containing lists or dictionaries or other mutabletypes that are compared by value rather than by object identity, thereason being that the efficient implementation of dictionariesrequires a key's hash value to remain constant.Numeric types used for keys obey the normal rules for numericcomparison: if two numbers compare equal (e.g., \code{1} and\code{1.0}) then they can be used interchangeably to index the samedictionary entry. Dictionaries are mutable; they can be created by the\code{\{...\}} notation (see section~\ref{dict}, ``DictionaryDisplays''). The extension modules \module{dbm}\refstmodindex{dbm},\module{gdbm}\refstmodindex{gdbm}, and\module{bsddb}\refstmodindex{bsddb} provide additional examples ofmapping types. \end{description} % Mapping types \item[Callable types]These\obindex{callable} are the types to which the function calloperation (see section~\ref{calls}, ``Calls'') can be applied:\indexii{function}{call}\index{invocation}\indexii{function}{argument} \begin{description} \item[User-defined functions]A user-defined function object is created by a function definition(see section~\ref{function}, ``Function definitions'').  It should becalled with an argumentlist containing the same number of items as the function's formalparameter list.\indexii{user-defined}{function}\obindex{function}\obindex{user-defined function} Special attributes:  \begin{tableiii}{lll}{member}{Attribute}{Meaning}{}  \lineiii{func_doc}{The function's documentation string, or    \code{None} if unavailable}{Writable}   \lineiii{__doc__}{Another way of spelling    \member{func_doc}}{Writable}   \lineiii{func_name}{The function's name}{Writable}   \lineiii{__name__}{Another way of spelling    \member{func_name}}{Writable}   \lineiii{__module__}{The name of the module the function was defined    in, or \code{None} if unavailable.}{Writable}   \lineiii{func_defaults}{A tuple containing default argument values    for those arguments that have defaults, or \code{None} if no    arguments have a default value}{Writable}   \lineiii{func_code}{The code object representing the compiled    function body.}{Writable}   \lineiii{func_globals}{A reference to the dictionary that holds the    function's global variables --- the global namespace of the module    in which the function was defined.}{Read-only}

Lines 1–500 of 2225.