- document bytes()
- throw out many mentions of "old-style/new-style" - add memoryview() though I somebody has to fill in the details - throw out str.decode() - throw out classobj and instanceobj
This commit is contained in:
parent
3540ef16c1
commit
85eb8c103c
|
@ -2503,43 +2503,6 @@ Dictionary Objects
|
|||
Other Objects
|
||||
=============
|
||||
|
||||
|
||||
.. _classobjects:
|
||||
|
||||
Class Objects
|
||||
-------------
|
||||
|
||||
.. index:: object: class
|
||||
|
||||
Note that the class objects described here represent old-style classes, which
|
||||
will go away in Python 3. When creating new types for extension modules, you
|
||||
will want to work with type objects (section :ref:`typeobjects`).
|
||||
|
||||
|
||||
.. ctype:: PyClassObject
|
||||
|
||||
The C structure of the objects used to describe built-in classes.
|
||||
|
||||
|
||||
.. cvar:: PyObject* PyClass_Type
|
||||
|
||||
.. index:: single: ClassType (in module types)
|
||||
|
||||
This is the type object for class objects; it is the same object as
|
||||
``types.ClassType`` in the Python layer.
|
||||
|
||||
|
||||
.. cfunction:: int PyClass_Check(PyObject *o)
|
||||
|
||||
Return true if the object *o* is a class object, including instances of types
|
||||
derived from the standard class object. Return false in all other cases.
|
||||
|
||||
|
||||
.. cfunction:: int PyClass_IsSubclass(PyObject *klass, PyObject *base)
|
||||
|
||||
Return true if *klass* is a subclass of *base*. Return false in all other cases.
|
||||
|
||||
|
||||
.. _fileobjects:
|
||||
|
||||
File Objects
|
||||
|
@ -2668,40 +2631,6 @@ change in future releases of Python.
|
|||
failure; the appropriate exception will be set.
|
||||
|
||||
|
||||
.. _instanceobjects:
|
||||
|
||||
Instance Objects
|
||||
----------------
|
||||
|
||||
.. index:: object: instance
|
||||
|
||||
There are very few functions specific to instance objects.
|
||||
|
||||
|
||||
.. cvar:: PyTypeObject PyInstance_Type
|
||||
|
||||
Type object for class instances.
|
||||
|
||||
|
||||
.. cfunction:: int PyInstance_Check(PyObject *obj)
|
||||
|
||||
Return true if *obj* is an instance.
|
||||
|
||||
|
||||
.. cfunction:: PyObject* PyInstance_New(PyObject *class, PyObject *arg, PyObject *kw)
|
||||
|
||||
Create a new instance of a specific class. The parameters *arg* and *kw* are
|
||||
used as the positional and keyword parameters to the object's constructor.
|
||||
|
||||
|
||||
.. cfunction:: PyObject* PyInstance_NewRaw(PyObject *class, PyObject *dict)
|
||||
|
||||
Create a new instance of a specific class without calling its constructor.
|
||||
*class* is the class of new object. The *dict* parameter will be used as the
|
||||
object's :attr:`__dict__`; if *NULL*, a new dictionary will be created for the
|
||||
instance.
|
||||
|
||||
|
||||
.. _function-objects:
|
||||
|
||||
Function Objects
|
||||
|
|
|
@ -750,6 +750,7 @@ return true, otherwise they return false and raise an appropriate exception.
|
|||
va_list rather than a variable number of arguments.
|
||||
|
||||
|
||||
.. XXX deprecated, will be removed
|
||||
.. cfunction:: int PyArg_Parse(PyObject *args, const char *format, ...)
|
||||
|
||||
Function used to deconstruct the argument lists of "old-style" functions ---
|
||||
|
|
|
@ -29,8 +29,8 @@ Glossary
|
|||
bytecode.
|
||||
|
||||
classic class
|
||||
Any class which does not inherit from :class:`object`. See
|
||||
:term:`new-style class`.
|
||||
One of the two flavors of classes in earlier Python versions. Since
|
||||
Python 3.0, there are no classic classes anymore.
|
||||
|
||||
coercion
|
||||
The implicit conversion of an instance of one type to another during an
|
||||
|
@ -58,15 +58,14 @@ Glossary
|
|||
it's almost certain you can safely ignore them.
|
||||
|
||||
descriptor
|
||||
Any *new-style* object that defines the methods :meth:`__get__`,
|
||||
:meth:`__set__`, or :meth:`__delete__`. When a class attribute is a
|
||||
descriptor, its special binding behavior is triggered upon attribute
|
||||
lookup. Normally, writing *a.b* looks up the object *b* in the class
|
||||
dictionary for *a*, but if *b* is a descriptor, the defined method gets
|
||||
called. Understanding descriptors is a key to a deep understanding of
|
||||
Python because they are the basis for many features including functions,
|
||||
methods, properties, class methods, static methods, and reference to super
|
||||
classes.
|
||||
An object that defines the methods :meth:`__get__`, :meth:`__set__`, or
|
||||
:meth:`__delete__`. When a class attribute is a descriptor, its special
|
||||
binding behavior is triggered upon attribute lookup. Normally, writing
|
||||
*a.b* looks up the object *b* in the class dictionary for *a*, but if *b*
|
||||
is a descriptor, the defined method gets called. Understanding
|
||||
descriptors is a key to a deep understanding of Python because they are
|
||||
the basis for many features including functions, methods, properties,
|
||||
class methods, static methods, and reference to super classes.
|
||||
|
||||
dictionary
|
||||
An associative array, where arbitrary keys are mapped to values. The use
|
||||
|
@ -277,11 +276,10 @@ Glossary
|
|||
scope. Likewise, global variables read and write to the global namespace.
|
||||
|
||||
new-style class
|
||||
Any class that inherits from :class:`object`. This includes all built-in
|
||||
types like :class:`list` and :class:`dict`. Only new-style classes can
|
||||
use Python's newer, versatile features like :attr:`__slots__`,
|
||||
descriptors, properties, :meth:`__getattribute__`, class methods, and
|
||||
static methods.
|
||||
Old name for the flavor of classes now used for all class objects. In
|
||||
earlier Python versions, only new-style classes could use Python's newer,
|
||||
versatile features like :attr:`__slots__`, descriptors, properties,
|
||||
:meth:`__getattribute__`, class methods, and static methods.
|
||||
|
||||
Python 3000
|
||||
Nickname for the next major Python version, 3.0 (coined long ago when the
|
||||
|
@ -294,11 +292,11 @@ Glossary
|
|||
implementation level to keep track of allocated memory.
|
||||
|
||||
__slots__
|
||||
A declaration inside a :term:`new-style class` that saves memory by
|
||||
pre-declaring space for instance attributes and eliminating instance
|
||||
dictionaries. Though popular, the technique is somewhat tricky to get
|
||||
right and is best reserved for rare cases where there are large numbers of
|
||||
instances in a memory-critical application.
|
||||
A declaration inside a class that saves memory by pre-declaring space for
|
||||
instance attributes and eliminating instance dictionaries. Though
|
||||
popular, the technique is somewhat tricky to get right and is best
|
||||
reserved for rare cases where there are large numbers of instances in a
|
||||
memory-critical application.
|
||||
|
||||
sequence
|
||||
An :term:`iterable` which supports efficient element access using integer
|
||||
|
|
|
@ -139,12 +139,37 @@ available. They are listed here in alphabetical order.
|
|||
If no argument is given, this function returns :const:`False`.
|
||||
|
||||
|
||||
.. function:: bytes([arg[, encoding[, errors]]])
|
||||
|
||||
Return a new array of bytes. The :class:`bytes` type is a mutable sequence
|
||||
of integers in the range 0 <= x < 256. It has most of the usual methods of
|
||||
mutable sequences, described in :ref:`typesseq-mutable`, as well as a few
|
||||
methods borrowed from strings, described in :ref:`bytes-methods`.
|
||||
|
||||
The optional *arg* parameter can be used to initialize the array in a few
|
||||
different ways:
|
||||
|
||||
* If it is a *string*, you must also give the *encoding* (and optionally,
|
||||
*errors*) parameters; :func:`bytes` then acts like :meth:`str.encode`.
|
||||
|
||||
* If it is an *integer*, the array will have that size and will be
|
||||
initialized with null bytes.
|
||||
|
||||
* If it is an object conforming to the *buffer* interface, a read-only buffer
|
||||
of the object will be used to initialize the bytes array.
|
||||
|
||||
* If it is an *iterable*, it must be an iterable of integers in the range 0
|
||||
<= x < 256, which are used as the initial contents of the array.
|
||||
|
||||
Without an argument, an array of size 0 is created.
|
||||
|
||||
|
||||
.. function:: chr(i)
|
||||
|
||||
Return the string of one character whose Unicode codepoint is the integer *i*. For
|
||||
example, ``chr(97)`` returns the string ``'a'``. This is the inverse of
|
||||
:func:`ord`. The valid range for the argument depends how Python was
|
||||
configured -- it may be either UCS2 [0..0xFFFF] or UCS4 [0..0x10FFFF].
|
||||
Return the string of one character whose Unicode codepoint is the integer
|
||||
*i*. For example, ``chr(97)`` returns the string ``'a'``. This is the
|
||||
inverse of :func:`ord`. The valid range for the argument depends how Python
|
||||
was configured -- it may be either UCS2 [0..0xFFFF] or UCS4 [0..0x10FFFF].
|
||||
:exc:`ValueError` will be raised if *i* is outside that range.
|
||||
|
||||
|
||||
|
@ -557,15 +582,13 @@ available. They are listed here in alphabetical order.
|
|||
|
||||
.. function:: isinstance(object, classinfo)
|
||||
|
||||
Return true if the *object* argument is an instance of the *classinfo* argument,
|
||||
or of a (direct or indirect) subclass thereof. Also return true if *classinfo*
|
||||
is a type object (new-style class) and *object* is an object of that type or of
|
||||
a (direct or indirect) subclass thereof. If *object* is not a class instance or
|
||||
an object of the given type, the function always returns false. If *classinfo*
|
||||
is neither a class object nor a type object, it may be a tuple of class or type
|
||||
objects, or may recursively contain other such tuples (other sequence types are
|
||||
not accepted). If *classinfo* is not a class, type, or tuple of classes, types,
|
||||
and such tuples, a :exc:`TypeError` exception is raised.
|
||||
Return true if the *object* argument is an instance of the *classinfo*
|
||||
argument, or of a (direct or indirect) subclass thereof. If *object* is not
|
||||
an object of the given type, the function always returns false. If
|
||||
*classinfo* is not a class (type object), it may be a tuple of type objects,
|
||||
or may recursively contain other such tuples (other sequence types are not
|
||||
accepted). If *classinfo* is not a type or tuple of types and such tuples,
|
||||
a :exc:`TypeError` exception is raised.
|
||||
|
||||
.. versionchanged:: 2.2
|
||||
Support for a tuple of type information was added.
|
||||
|
@ -659,6 +682,13 @@ available. They are listed here in alphabetical order.
|
|||
Added support for the optional *key* argument.
|
||||
|
||||
|
||||
.. function:: memoryview(obj)
|
||||
|
||||
Return a "memory view" object created from the given argument.
|
||||
|
||||
XXX: To be documented.
|
||||
|
||||
|
||||
.. function:: min(iterable[, args...][key])
|
||||
|
||||
With a single argument *iterable*, return the smallest item of a non-empty
|
||||
|
@ -682,9 +712,13 @@ available. They are listed here in alphabetical order.
|
|||
|
||||
.. function:: object()
|
||||
|
||||
Return a new featureless object. :class:`object` is a base for all new style
|
||||
classes. It has the methods that are common to all instances of new style
|
||||
classes.
|
||||
Return a new featureless object. :class:`object` is a base for all classes.
|
||||
It has the methods that are common to all instances of Python classes.
|
||||
|
||||
.. note::
|
||||
|
||||
:class:`object` does *not* have a :attr:`__dict__`, so you can't assign
|
||||
arbitrary attributes to an instance of the :class:`object` class.
|
||||
|
||||
.. versionadded:: 2.2
|
||||
|
||||
|
@ -797,8 +831,7 @@ available. They are listed here in alphabetical order.
|
|||
|
||||
.. function:: property([fget[, fset[, fdel[, doc]]]])
|
||||
|
||||
Return a property attribute for new-style classes (classes that derive from
|
||||
:class:`object`).
|
||||
Return a property attribute.
|
||||
|
||||
*fget* is a function for getting an attribute value, likewise *fset* is a
|
||||
function for setting, and *fdel* a function for del'ing, an attribute. Typical
|
||||
|
@ -1023,11 +1056,12 @@ available. They are listed here in alphabetical order.
|
|||
|
||||
.. function:: super(type[, object-or-type])
|
||||
|
||||
.. XXX need to document PEP "new super"
|
||||
|
||||
Return the superclass of *type*. If the second argument is omitted the super
|
||||
object returned is unbound. If the second argument is an object,
|
||||
``isinstance(obj, type)`` must be true. If the second argument is a type,
|
||||
``issubclass(type2, type)`` must be true. :func:`super` only works for new-style
|
||||
classes.
|
||||
``issubclass(type2, type)`` must be true.
|
||||
|
||||
A typical use for calling a cooperative superclass method is::
|
||||
|
||||
|
@ -1061,23 +1095,26 @@ available. They are listed here in alphabetical order.
|
|||
|
||||
.. index:: object: type
|
||||
|
||||
Return the type of an *object*. The return value is a type object. The
|
||||
:func:`isinstance` built-in function is recommended for testing the type of an
|
||||
object.
|
||||
Return the type of an *object*. The return value is a type object and
|
||||
generally the same object as returned by ``object.__class__``.
|
||||
|
||||
With three arguments, :func:`type` functions as a constructor as detailed below.
|
||||
The :func:`isinstance` built-in function is recommended for testing the type
|
||||
of an object, because it takes subclasses into account.
|
||||
|
||||
With three arguments, :func:`type` functions as a constructor as detailed
|
||||
below.
|
||||
|
||||
|
||||
.. function:: type(name, bases, dict)
|
||||
:noindex:
|
||||
|
||||
Return a new type object. This is essentially a dynamic form of the
|
||||
:keyword:`class` statement. The *name* string is the class name and becomes the
|
||||
:attr:`__name__` attribute; the *bases* tuple itemizes the base classes and
|
||||
becomes the :attr:`__bases__` attribute; and the *dict* dictionary is the
|
||||
namespace containing definitions for class body and becomes the :attr:`__dict__`
|
||||
attribute. For example, the following two statements create identical
|
||||
:class:`type` objects::
|
||||
:keyword:`class` statement. The *name* string is the class name and becomes
|
||||
the :attr:`__name__` attribute; the *bases* tuple itemizes the base classes
|
||||
and becomes the :attr:`__bases__` attribute; and the *dict* dictionary is the
|
||||
namespace containing definitions for class body and becomes the
|
||||
:attr:`__dict__` attribute. For example, the following two statements create
|
||||
identical :class:`type` objects::
|
||||
|
||||
>>> class X(object):
|
||||
... a = 1
|
||||
|
@ -1128,6 +1165,7 @@ Python programmers, trainers, students and bookwriters should feel free to
|
|||
bypass these functions without concerns about missing something important.
|
||||
|
||||
|
||||
.. XXX does this go away?
|
||||
.. function:: buffer(object[, offset[, size]])
|
||||
|
||||
The *object* argument must be an object that supports the buffer call interface
|
||||
|
|
|
@ -416,6 +416,8 @@ Pickling and unpickling normal class instances
|
|||
single: __getinitargs__() (copy protocol)
|
||||
single: __init__() (instance constructor)
|
||||
|
||||
.. XXX is __getinitargs__ only used with old-style classes?
|
||||
|
||||
When a pickled class instance is unpickled, its :meth:`__init__` method is
|
||||
normally *not* invoked. If it is desirable that the :meth:`__init__` method be
|
||||
called on unpickling, an old-style class can define a method
|
||||
|
|
|
@ -547,11 +547,6 @@ Registering an adapter callable
|
|||
The other possibility is to create a function that converts the type to the
|
||||
string representation and register the function with :meth:`register_adapter`.
|
||||
|
||||
.. note::
|
||||
|
||||
The type/class to adapt must be a new-style class, i. e. it must have
|
||||
:class:`object` as one of its bases.
|
||||
|
||||
.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
|
||||
|
||||
The :mod:`sqlite3` module has two default adapters for Python's built-in
|
||||
|
|
|
@ -682,22 +682,6 @@ the :mod:`re` module for string functions based on regular expressions.
|
|||
slice notation.
|
||||
|
||||
|
||||
.. XXX what about str.decode???
|
||||
.. method:: str.decode([encoding[, errors]])
|
||||
|
||||
Decode the string using the codec registered for *encoding*. *encoding*
|
||||
defaults to the default string encoding. *errors* may be given to set a
|
||||
different error handling scheme. The default is ``'strict'``, meaning that
|
||||
encoding errors raise :exc:`UnicodeError`. Other possible values are
|
||||
``'ignore'``, ``'replace'`` and any other name registered via
|
||||
:func:`codecs.register_error`, see section :ref:`codec-base-classes`.
|
||||
|
||||
.. versionadded:: 2.2
|
||||
|
||||
.. versionchanged:: 2.3
|
||||
Support for other error handling schemes added.
|
||||
|
||||
|
||||
.. method:: str.encode([encoding[, errors]])
|
||||
|
||||
Return an encoded version of the string. Default encoding is the current
|
||||
|
|
|
@ -540,8 +540,10 @@ must be given a value in the :meth:`__init__` method or in another method. Both
|
|||
class and instance variables are accessible through the notation
|
||||
"``self.name``", and an instance variable hides a class variable with the same
|
||||
name when accessed in this way. Class variables with immutable values can be
|
||||
used as defaults for instance variables. For new-style classes, descriptors can
|
||||
be used to create instance variables with different implementation details.
|
||||
used as defaults for instance variables. Descriptors can be used to create
|
||||
instance variables with different implementation details.
|
||||
|
||||
.. XXX add link to descriptor docs above
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
|
|
|
@ -29,11 +29,14 @@ represented by objects.)
|
|||
single: mutable object
|
||||
single: immutable object
|
||||
|
||||
.. XXX it *is* now possible in some cases to change an object's
|
||||
type, under certain controlled conditions
|
||||
|
||||
Every object has an identity, a type and a value. An object's *identity* never
|
||||
changes once it has been created; you may think of it as the object's address in
|
||||
memory. The ':keyword:`is`' operator compares the identity of two objects; the
|
||||
:func:`id` function returns an integer representing its identity (currently
|
||||
implemented as its address). An object's :dfn:`type` is also unchangeable. [#]_
|
||||
implemented as its address). An object's :dfn:`type` is also unchangeable.
|
||||
An object's type determines the operations that the object supports (e.g., "does
|
||||
it have a length?") and also defines the possible values for objects of that
|
||||
type. The :func:`type` function returns an object's type (which is an object
|
||||
|
@ -688,31 +691,17 @@ Callable types
|
|||
this case, the special read-only attribute :attr:`__self__` is set to the object
|
||||
denoted by *list*.
|
||||
|
||||
Class Types
|
||||
Class types, or "new-style classes," are callable. These objects normally act
|
||||
as factories for new instances of themselves, but variations are possible for
|
||||
class types that override :meth:`__new__`. The arguments of the call are passed
|
||||
to :meth:`__new__` and, in the typical case, to :meth:`__init__` to initialize
|
||||
the new instance.
|
||||
Classes
|
||||
Classes are callable. These objects normally act as factories for new
|
||||
instances of themselves, but variations are possible for class types that
|
||||
override :meth:`__new__`. The arguments of the call are passed to
|
||||
:meth:`__new__` and, in the typical case, to :meth:`__init__` to
|
||||
initialize the new instance.
|
||||
|
||||
Classic Classes
|
||||
.. index::
|
||||
single: __init__() (object method)
|
||||
object: class
|
||||
object: class instance
|
||||
object: instance
|
||||
pair: class object; call
|
||||
Class Instances
|
||||
Instances of arbitrary classes can be made callable by defining a
|
||||
:meth:`__call__` method in their class.
|
||||
|
||||
Class objects are described below. When a class object is called, a new class
|
||||
instance (also described below) is created and returned. This implies a call to
|
||||
the class's :meth:`__init__` method if it has one. Any arguments are passed on
|
||||
to the :meth:`__init__` method. If there is no :meth:`__init__` method, the
|
||||
class must be called without arguments.
|
||||
|
||||
Class instances
|
||||
Class instances are described below. Class instances are callable only when the
|
||||
class has a :meth:`__call__` method; ``x(arguments)`` is a shorthand for
|
||||
``x.__call__(arguments)``.
|
||||
|
||||
Modules
|
||||
.. index::
|
||||
|
@ -752,7 +741,10 @@ Modules
|
|||
extension modules loaded dynamically from a shared library, it is the pathname
|
||||
of the shared library file.
|
||||
|
||||
Classes
|
||||
.. XXX "Classes" and "Instances" is outdated!
|
||||
see http://www.python.org/doc/newstyle.html for newstyle information
|
||||
|
||||
Custom classes
|
||||
Class objects are created by class definitions (see section :ref:`class`). A
|
||||
class has a namespace implemented by a dictionary object. Class attribute
|
||||
references are translated to lookups in this dictionary, e.g., ``C.x`` is
|
||||
|
@ -760,6 +752,8 @@ Classes
|
|||
there, the attribute search continues in the base classes. The search is
|
||||
depth-first, left-to-right in the order of occurrence in the base class list.
|
||||
|
||||
.. XXX document descriptors and new MRO
|
||||
|
||||
.. index::
|
||||
object: class
|
||||
object: class instance
|
||||
|
@ -1077,53 +1071,6 @@ Internal types
|
|||
|
||||
.. % Internal types
|
||||
|
||||
.. % Types
|
||||
.. % =========================================================================
|
||||
|
||||
|
||||
New-style and classic classes
|
||||
=============================
|
||||
|
||||
Classes and instances come in two flavors: old-style or classic, and new-style.
|
||||
|
||||
Up to Python 2.1, old-style classes were the only flavour available to the user.
|
||||
The concept of (old-style) class is unrelated to the concept of type: if *x* is
|
||||
an instance of an old-style class, then ``x.__class__`` designates the class of
|
||||
*x*, but ``type(x)`` is always ``<type 'instance'>``. This reflects the fact
|
||||
that all old-style instances, independently of their class, are implemented with
|
||||
a single built-in type, called ``instance``.
|
||||
|
||||
New-style classes were introduced in Python 2.2 to unify classes and types. A
|
||||
new-style class neither more nor less than a user-defined type. If *x* is an
|
||||
instance of a new-style class, then ``type(x)`` is the same as ``x.__class__``.
|
||||
|
||||
The major motivation for introducing new-style classes is to provide a unified
|
||||
object model with a full meta-model. It also has a number of immediate
|
||||
benefits, like the ability to subclass most built-in types, or the introduction
|
||||
of "descriptors", which enable computed properties.
|
||||
|
||||
For compatibility reasons, classes are still old-style by default. New-style
|
||||
classes are created by specifying another new-style class (i.e. a type) as a
|
||||
parent class, or the "top-level type" :class:`object` if no other parent is
|
||||
needed. The behaviour of new-style classes differs from that of old-style
|
||||
classes in a number of important details in addition to what :func:`type`
|
||||
returns. Some of these changes are fundamental to the new object model, like
|
||||
the way special methods are invoked. Others are "fixes" that could not be
|
||||
implemented before for compatibility concerns, like the method resolution order
|
||||
in case of multiple inheritance.
|
||||
|
||||
This manual is not up-to-date with respect to new-style classes. For now,
|
||||
please see http://www.python.org/doc/newstyle.html for more information.
|
||||
|
||||
.. index::
|
||||
single: class
|
||||
single: class
|
||||
single: class
|
||||
|
||||
The plan is to eventually drop old-style classes, leaving only the semantics of
|
||||
new-style classes. This change will probably only be feasible in Python 3.0.
|
||||
new-style classic old-style
|
||||
|
||||
.. % =========================================================================
|
||||
|
||||
|
||||
|
@ -1141,10 +1088,12 @@ A class can implement certain operations that are invoked by special syntax
|
|||
with special names. This is Python's approach to :dfn:`operator overloading`,
|
||||
allowing classes to define their own behavior with respect to language
|
||||
operators. For instance, if a class defines a method named :meth:`__getitem__`,
|
||||
and ``x`` is an instance of this class, then ``x[i]`` is equivalent [#]_ to
|
||||
and ``x`` is an instance of this class, then ``x[i]`` is equivalent to
|
||||
``x.__getitem__(i)``. Except where mentioned, attempts to execute an operation
|
||||
raise an exception when no appropriate method is defined.
|
||||
|
||||
.. XXX above translation is not correct for new-style classes!
|
||||
|
||||
When implementing a class that emulates any built-in type, it is important that
|
||||
the emulation only be implemented to the degree that it makes sense for the
|
||||
object being modelled. For example, some sequences may work well with retrieval
|
||||
|
@ -1423,6 +1372,8 @@ Customizing attribute access
|
|||
The following methods can be defined to customize the meaning of attribute
|
||||
access (use of, assignment to, or deletion of ``x.name``) for class instances.
|
||||
|
||||
.. XXX explain how descriptors interfere here!
|
||||
|
||||
|
||||
.. method:: object.__getattr__(self, name)
|
||||
|
||||
|
@ -1431,8 +1382,6 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
|
|||
``self``). ``name`` is the attribute name. This method should return the
|
||||
(computed) attribute value or raise an :exc:`AttributeError` exception.
|
||||
|
||||
.. index:: single: __setattr__() (object method)
|
||||
|
||||
Note that if the attribute is found through the normal mechanism,
|
||||
:meth:`__getattr__` is not called. (This is an intentional asymmetry between
|
||||
:meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency
|
||||
|
@ -1440,39 +1389,8 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
|
|||
other attributes of the instance. Note that at least for instance variables,
|
||||
you can fake total control by not inserting any values in the instance attribute
|
||||
dictionary (but instead inserting them in another object). See the
|
||||
:meth:`__getattribute__` method below for a way to actually get total control in
|
||||
new-style classes.
|
||||
|
||||
|
||||
.. method:: object.__setattr__(self, name, value)
|
||||
|
||||
Called when an attribute assignment is attempted. This is called instead of the
|
||||
normal mechanism (i.e. store the value in the instance dictionary). *name* is
|
||||
the attribute name, *value* is the value to be assigned to it.
|
||||
|
||||
.. index:: single: __dict__ (instance attribute)
|
||||
|
||||
If :meth:`__setattr__` wants to assign to an instance attribute, it should not
|
||||
simply execute ``self.name = value`` --- this would cause a recursive call to
|
||||
itself. Instead, it should insert the value in the dictionary of instance
|
||||
attributes, e.g., ``self.__dict__[name] = value``. For new-style classes,
|
||||
rather than accessing the instance dictionary, it should call the base class
|
||||
method with the same name, for example, ``object.__setattr__(self, name,
|
||||
value)``.
|
||||
|
||||
|
||||
.. method:: object.__delattr__(self, name)
|
||||
|
||||
Like :meth:`__setattr__` but for attribute deletion instead of assignment. This
|
||||
should only be implemented if ``del obj.name`` is meaningful for the object.
|
||||
|
||||
|
||||
.. _new-style-attribute-access:
|
||||
|
||||
More attribute access for new-style classes
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The following methods only apply to new-style classes.
|
||||
:meth:`__getattribute__` method below for a way to actually get total control
|
||||
over attribute access.
|
||||
|
||||
|
||||
.. method:: object.__getattribute__(self, name)
|
||||
|
@ -1487,6 +1405,23 @@ The following methods only apply to new-style classes.
|
|||
``object.__getattribute__(self, name)``.
|
||||
|
||||
|
||||
.. method:: object.__setattr__(self, name, value)
|
||||
|
||||
Called when an attribute assignment is attempted. This is called instead of
|
||||
the normal mechanism (i.e. store the value in the instance dictionary).
|
||||
*name* is the attribute name, *value* is the value to be assigned to it.
|
||||
|
||||
If :meth:`__setattr__` wants to assign to an instance attribute, it should
|
||||
call the base class method with the same name, for example,
|
||||
``object.__setattr__(self, name, value)``.
|
||||
|
||||
|
||||
.. method:: object.__delattr__(self, name)
|
||||
|
||||
Like :meth:`__setattr__` but for attribute deletion instead of assignment. This
|
||||
should only be implemented if ``del obj.name`` is meaningful for the object.
|
||||
|
||||
|
||||
.. _descriptors:
|
||||
|
||||
Implementing Descriptors
|
||||
|
@ -1494,10 +1429,9 @@ Implementing Descriptors
|
|||
|
||||
The following methods only apply when an instance of the class containing the
|
||||
method (a so-called *descriptor* class) appears in the class dictionary of
|
||||
another new-style class, known as the *owner* class. In the examples below, "the
|
||||
another class, known as the *owner* class. In the examples below, "the
|
||||
attribute" refers to the attribute whose name is the key of the property in the
|
||||
owner class' ``__dict__``. Descriptors can only be implemented as new-style
|
||||
classes themselves.
|
||||
owner class' :attr:`__dict__`.
|
||||
|
||||
|
||||
.. method:: object.__get__(self, instance, owner)
|
||||
|
@ -1551,11 +1485,11 @@ Direct Call
|
|||
descriptor method: ``x.__get__(a)``.
|
||||
|
||||
Instance Binding
|
||||
If binding to a new-style object instance, ``a.x`` is transformed into the call:
|
||||
If binding to an object instance, ``a.x`` is transformed into the call:
|
||||
``type(a).__dict__['x'].__get__(a, type(a))``.
|
||||
|
||||
Class Binding
|
||||
If binding to a new-style class, ``A.x`` is transformed into the call:
|
||||
If binding to a class, ``A.x`` is transformed into the call:
|
||||
``A.__dict__['x'].__get__(None, A)``.
|
||||
|
||||
Super Binding
|
||||
|
@ -1585,23 +1519,22 @@ instances cannot override the behavior of a property.
|
|||
__slots__
|
||||
^^^^^^^^^
|
||||
|
||||
By default, instances of both old and new-style classes have a dictionary for
|
||||
attribute storage. This wastes space for objects having very few instance
|
||||
variables. The space consumption can become acute when creating large numbers
|
||||
of instances.
|
||||
By default, instances of classes have a dictionary for attribute storage. This
|
||||
wastes space for objects having very few instance variables. The space
|
||||
consumption can become acute when creating large numbers of instances.
|
||||
|
||||
The default can be overridden by defining *__slots__* in a new-style class
|
||||
definition. The *__slots__* declaration takes a sequence of instance variables
|
||||
and reserves just enough space in each instance to hold a value for each
|
||||
variable. Space is saved because *__dict__* is not created for each instance.
|
||||
The default can be overridden by defining *__slots__* in a class definition.
|
||||
The *__slots__* declaration takes a sequence of instance variables and reserves
|
||||
just enough space in each instance to hold a value for each variable. Space is
|
||||
saved because *__dict__* is not created for each instance.
|
||||
|
||||
|
||||
.. data:: __slots__
|
||||
.. data:: object.__slots__
|
||||
|
||||
This class variable can be assigned a string, iterable, or sequence of strings
|
||||
with variable names used by instances. If defined in a new-style class,
|
||||
*__slots__* reserves space for the declared variables and prevents the automatic
|
||||
creation of *__dict__* and *__weakref__* for each instance.
|
||||
This class variable can be assigned a string, iterable, or sequence of
|
||||
strings with variable names used by instances. If defined in a new-style
|
||||
class, *__slots__* reserves space for the declared variables and prevents the
|
||||
automatic creation of *__dict__* and *__weakref__* for each instance.
|
||||
|
||||
.. versionadded:: 2.2
|
||||
|
||||
|
@ -1610,8 +1543,8 @@ Notes on using *__slots__*
|
|||
* Without a *__dict__* variable, instances cannot be assigned new variables not
|
||||
listed in the *__slots__* definition. Attempts to assign to an unlisted
|
||||
variable name raises :exc:`AttributeError`. If dynamic assignment of new
|
||||
variables is desired, then add ``'__dict__'`` to the sequence of strings in the
|
||||
*__slots__* declaration.
|
||||
variables is desired, then add ``'__dict__'`` to the sequence of strings in
|
||||
the *__slots__* declaration.
|
||||
|
||||
.. versionchanged:: 2.3
|
||||
Previously, adding ``'__dict__'`` to the *__slots__* declaration would not
|
||||
|
@ -1661,9 +1594,9 @@ Notes on using *__slots__*
|
|||
Customizing class creation
|
||||
--------------------------
|
||||
|
||||
By default, new-style classes are constructed using :func:`type`. A class
|
||||
definition is read into a separate namespace and the value of class name is
|
||||
bound to the result of ``type(name, bases, dict)``.
|
||||
By default, classes are constructed using :func:`type`. A class definition is
|
||||
read into a separate namespace and the value of class name is bound to the
|
||||
result of ``type(name, bases, dict)``.
|
||||
|
||||
When the class definition is read, if *__metaclass__* is defined then the
|
||||
callable assigned to it will be called instead of :func:`type`. The allows
|
||||
|
@ -1675,7 +1608,7 @@ process:
|
|||
* Returning an instance of another class -- essentially performing the role of a
|
||||
factory function.
|
||||
|
||||
|
||||
.. XXX needs to be updated for the "new metaclasses" PEP
|
||||
.. data:: __metaclass__
|
||||
|
||||
This variable can be any callable accepting arguments for ``name``, ``bases``,
|
||||
|
@ -1693,7 +1626,7 @@ The appropriate metaclass is determined by the following precedence rules:
|
|||
|
||||
* Otherwise, if a global variable named __metaclass__ exists, it is used.
|
||||
|
||||
* Otherwise, the old-style, classic metaclass (types.ClassType) is used.
|
||||
* Otherwise, the default metaclass (:class:`type`) is used.
|
||||
|
||||
The potential uses for metaclasses are boundless. Some ideas that have been
|
||||
explored including logging, interface checking, automatic delegation, automatic
|
||||
|
@ -2124,18 +2057,6 @@ For more information on context managers, see :ref:`typecontextmanager`.
|
|||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
.. [#] Since Python 2.2, a gradual merging of types and classes has been started that
|
||||
makes this and a few other assertions made in this manual not 100% accurate and
|
||||
complete: for example, it *is* now possible in some cases to change an object's
|
||||
type, under certain controlled conditions. Until this manual undergoes
|
||||
extensive revision, it must now be taken as authoritative only regarding
|
||||
"classic classes", that are still the default, for compatibility purposes, in
|
||||
Python 2.2 and 2.3. For more information, see
|
||||
http://www.python.org/doc/newstyle.html.
|
||||
|
||||
.. [#] This, and other statements, are only roughly true for instances of new-style
|
||||
classes.
|
||||
|
||||
.. [#] A descriptor can define any combination of :meth:`__get__`,
|
||||
:meth:`__set__` and :meth:`__delete__`. If it does not define :meth:`__get__`,
|
||||
then accessing the attribute even on an instance will return the descriptor
|
||||
|
|
|
@ -483,36 +483,27 @@ definition with multiple base classes looks like this::
|
|||
.
|
||||
<statement-N>
|
||||
|
||||
For old-style classes, the only rule is depth-first, left-to-right. Thus, if an
|
||||
attribute is not found in :class:`DerivedClassName`, it is searched in
|
||||
:class:`Base1`, then (recursively) in the base classes of :class:`Base1`, and
|
||||
only if it is not found there, it is searched in :class:`Base2`, and so on.
|
||||
Formerly, the only rule was depth-first, left-to-right. Thus, if an attribute
|
||||
was not found in :class:`DerivedClassName`, it was searched in :class:`Base1`,
|
||||
then (recursively) in the base classes of :class:`Base1`, and only if it was not
|
||||
found there, it was searched in :class:`Base2`, and so on.
|
||||
|
||||
(To some people breadth first --- searching :class:`Base2` and :class:`Base3`
|
||||
before the base classes of :class:`Base1` --- looks more natural. However, this
|
||||
would require you to know whether a particular attribute of :class:`Base1` is
|
||||
actually defined in :class:`Base1` or in one of its base classes before you can
|
||||
figure out the consequences of a name conflict with an attribute of
|
||||
:class:`Base2`. The depth-first rule makes no differences between direct and
|
||||
inherited attributes of :class:`Base1`.)
|
||||
In the meantime, the method resolution order changes dynamically to support
|
||||
cooperative calls to :func:`super`. This approach is known in some other
|
||||
multiple-inheritance languages as call-next-method and is more powerful than the
|
||||
super call found in single-inheritance languages.
|
||||
|
||||
For new-style classes, the method resolution order changes dynamically to
|
||||
support cooperative calls to :func:`super`. This approach is known in some
|
||||
other multiple-inheritance languages as call-next-method and is more powerful
|
||||
than the super call found in single-inheritance languages.
|
||||
|
||||
With new-style classes, dynamic ordering is necessary because all cases of
|
||||
multiple inheritance exhibit one or more diamond relationships (where one at
|
||||
least one of the parent classes can be accessed through multiple paths from the
|
||||
bottommost class). For example, all new-style classes inherit from
|
||||
:class:`object`, so any case of multiple inheritance provides more than one path
|
||||
to reach :class:`object`. To keep the base classes from being accessed more
|
||||
than once, the dynamic algorithm linearizes the search order in a way that
|
||||
preserves the left-to-right ordering specified in each class, that calls each
|
||||
parent only once, and that is monotonic (meaning that a class can be subclassed
|
||||
without affecting the precedence order of its parents). Taken together, these
|
||||
properties make it possible to design reliable and extensible classes with
|
||||
multiple inheritance. For more detail, see
|
||||
Dynamic ordering is necessary because all cases of multiple inheritance exhibit
|
||||
one or more diamond relationships (where one at least one of the parent classes
|
||||
can be accessed through multiple paths from the bottommost class). For example,
|
||||
all classes inherit from :class:`object`, so any case of multiple inheritance
|
||||
provides more than one path to reach :class:`object`. To keep the base classes
|
||||
from being accessed more than once, the dynamic algorithm linearizes the search
|
||||
order in a way that preserves the left-to-right ordering specified in each
|
||||
class, that calls each parent only once, and that is monotonic (meaning that a
|
||||
class can be subclassed without affecting the precedence order of its parents).
|
||||
Taken together, these properties make it possible to design reliable and
|
||||
extensible classes with multiple inheritance. For more detail, see
|
||||
http://www.python.org/download/releases/2.3/mro/.
|
||||
|
||||
|
||||
|
|
Loading…
Reference in New Issue