Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Doc/tutorial/classes.rst

    r2 r391  
    55*******
    66
    7 Python's class mechanism adds classes to the language with a minimum of new
    8 syntax and semantics.  It is a mixture of the class mechanisms found in C++ and
    9 Modula-3.  As is true for modules, classes in Python do not put an absolute
    10 barrier between definition and user, but rather rely on the politeness of the
    11 user not to "break into the definition."  The most important features of classes
    12 are retained with full power, however: the class inheritance mechanism allows
     7Compared with other programming languages, Python's class mechanism adds classes
     8with a minimum of new syntax and semantics.  It is a mixture of the class
     9mechanisms found in C++ and Modula-3.  Python classes provide all the standard
     10features of Object Oriented Programming: the class inheritance mechanism allows
    1311multiple base classes, a derived class can override any methods of its base
    1412class or classes, and a method can call the method of a base class with the same
    15 name.  Objects can contain an arbitrary amount of data.
    16 
    17 In C++ terminology, all class members (including the data members) are *public*,
    18 and all member functions are *virtual*.  As in Modula-3, there are no shorthands
    19 for referencing the object's members from its methods: the method function is
    20 declared with an explicit first argument representing the object, which is
    21 provided implicitly by the call.  As in Smalltalk, classes themselves are
    22 objects.  This provides semantics for importing and renaming.  Unlike C++ and
    23 Modula-3, built-in types can be used as base classes for extension by the user.
    24 Also, like in C++, most built-in operators with special syntax (arithmetic
    25 operators, subscripting etc.) can be redefined for class instances.
     13name.  Objects can contain arbitrary amounts and kinds of data.  As is true for
     14modules, classes partake of the dynamic nature of Python: they are created at
     15runtime, and can be modified further after creation.
     16
     17In C++ terminology, normally class members (including the data members) are
     18*public* (except see below :ref:`tut-private`), and all member functions are
     19*virtual*.  As in Modula-3, there are no shorthands for referencing the object's
     20members from its methods: the method function is declared with an explicit first
     21argument representing the object, which is provided implicitly by the call.  As
     22in Smalltalk, classes themselves are objects.  This provides semantics for
     23importing and renaming.  Unlike C++ and Modula-3, built-in types can be used as
     24base classes for extension by the user.  Also, like in C++, most built-in
     25operators with special syntax (arithmetic operators, subscripting etc.) can be
     26redefined for class instances.
    2627
    2728(Lacking universally accepted terminology to talk about classes, I will make
     
    6566implemented as Python dictionaries, but that's normally not noticeable in any
    6667way (except for performance), and it may change in the future.  Examples of
    67 namespaces are: the set of built-in names (functions such as :func:`abs`, and
     68namespaces are: the set of built-in names (containing functions such as :func:`abs`, and
    6869built-in exception names); the global names in a module; and the local names in
    6970a function invocation.  In a sense the set of attributes of an object also form
     
    409410
    410411Methods may reference global names in the same way as ordinary functions.  The
    411 global scope associated with a method is the module containing the class
    412 definition.  (The class itself is never used as a global scope.)  While one
     412global scope associated with a method is the module containing its
     413definition.  (A class is never used as a global scope.)  While one
    413414rarely encounters a good reason for using global data in a method, there are
    414415many legitimate uses of the global scope: for one thing, functions and modules
     
    518519
    519520With new-style classes, dynamic ordering is necessary because all  cases of
    520 multiple inheritance exhibit one or more diamond relationships (where one at
     521multiple inheritance exhibit one or more diamond relationships (where at
    521522least one of the parent classes can be accessed through multiple paths from the
    522523bottommost class).  For example, all new-style classes inherit from
     
    534535.. _tut-private:
    535536
    536 Private Variables
    537 =================
     537Private Variables and Class-local References
     538============================================
    538539
    539540"Private" instance variables that cannot be accessed except from inside an
    540 object, don't exist in Python.  However, there is a convention that is followed
     541object don't exist in Python.  However, there is a convention that is followed
    541542by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should
    542543be treated as a non-public part of the API (whether it is a function, a method
     
    553554occurs within the definition of a class.
    554555
     556Name mangling is helpful for letting subclasses override methods without
     557breaking intraclass method calls.  For example::
     558
     559   class Mapping:
     560       def __init__(self, iterable):
     561           self.items_list = []
     562           self.__update(iterable)
     563
     564       def update(self, iterable):
     565           for item in iterable:
     566               self.items_list.append(item)
     567
     568       __update = update   # private copy of original update() method
     569
     570   class MappingSubclass(Mapping):
     571
     572       def update(self, keys, values):
     573           # provides new signature for update()
     574           # but does not break __init__()
     575           for item in zip(keys, values):
     576               self.items_list.append(item)
     577
    555578Note that the mangling rules are designed mostly to avoid accidents; it still is
    556579possible to access or modify a variable that is considered private.  This can
     
    587610passed a class that emulates the methods of that data type instead.  For
    588611instance, if you have a function that formats some data from a file object, you
    589 can define a class with methods :meth:`read` and :meth:`readline` that get the
     612can define a class with methods :meth:`read` and :meth:`!readline` that get the
    590613data from a string buffer instead, and pass it as an argument.
    591614
     
    666689       print char
    667690   for line in open("myfile.txt"):
    668        print line
     691       print line,
    669692
    670693This style of access is clear, concise, and convenient.  The use of iterators
    671694pervades and unifies Python.  Behind the scenes, the :keyword:`for` statement
    672695calls :func:`iter` on the container object.  The function returns an iterator
    673 object that defines the method :meth:`next` which accesses elements in the
    674 container one at a time.  When there are no more elements, :meth:`next` raises a
    675 :exc:`StopIteration` exception which tells the :keyword:`for` loop to terminate.
     696object that defines the method :meth:`~iterator.next` which accesses elements
     697in the container one at a time.  When there are no more elements,
     698:meth:`~iterator.next` raises a :exc:`StopIteration` exception which tells the
     699:keyword:`for` loop to terminate.
    676700This example shows how it all works::
    677701
     
    687711   'c'
    688712   >>> it.next()
    689 
    690713   Traceback (most recent call last):
    691714     File "<stdin>", line 1, in ?
     
    694717
    695718Having seen the mechanics behind the iterator protocol, it is easy to add
    696 iterator behavior to your classes.  Define a :meth:`__iter__` method which
     719iterator behavior to your classes.  Define an :meth:`__iter__` method which
    697720returns an object with a :meth:`next` method.  If the class defines
    698721:meth:`next`, then :meth:`__iter__` can just return ``self``::
    699722
    700723   class Reverse:
    701        "Iterator for looping over a sequence backwards"
     724       """Iterator for looping over a sequence backwards."""
    702725       def __init__(self, data):
    703726           self.data = data
     
    711734           return self.data[self.index]
    712735
    713    >>> for char in Reverse('spam'):
     736::
     737
     738   >>> rev = Reverse('spam')
     739   >>> iter(rev)
     740   <__main__.Reverse object at 0x00A1DB50>
     741   >>> for char in rev:
    714742   ...     print char
    715743   ...
     
    735763       for index in range(len(data)-1, -1, -1):
    736764           yield data[index]
     765
     766::
    737767
    738768   >>> for char in reverse('golf'):
Note: See TracChangeset for help on using the changeset viewer.