rest25/tutorial/classes.rst => rest262/tutorial/classes.rst
131It is important to realize that scopes are determined textually: the global
132scope of a function defined in a module is that module's namespace, no matter
133from where or by what alias the function is called.  On the other hand, the
134actual search for names is done dynamically, at run time --- however, the
135language definition is evolving towards static name resolution, at "compile"
136time, so don't rely on dynamic name resolution!  (In fact, local variables are
137already determined statically.)
138
n139-A special quirk of Python is that assignments always go into the innermost
n139+A special quirk of Python is that -- if no :keyword:`global`
140+statement is in effect -- assignments to names always go
140-scope.  Assignments do not copy data --- they just bind names to objects.  The
141+into the innermost scope.  Assignments do not copy data --- they just bind names
141-same is true for deletions: the statement ``del x`` removes the binding of ``x``
142+to objects.  The same is true for deletions: the statement ``del x`` removes the
142-from the namespace referenced by the local scope.  In fact, all operations that
143+binding of ``x`` from the namespace referenced by the local scope.  In fact, all
143-introduce new names use the local scope: in particular, import statements and
144+operations that introduce new names use the local scope: in particular, import
144-function definitions bind the module or function name in the local scope.  (The
145+statements and function definitions bind the module or function name in the
145-:keyword:`global` statement can be used to indicate that particular variables
146+local scope.  (The :keyword:`global` statement can be used to indicate that
146-live in the global scope.)
147+particular variables live in the global scope.)
147
148
149.. _tut-firstclasses:
150
151A First Look at Classes
152=======================
153
154Classes introduce a little bit of new syntax, three new object types, and some
202instantiation.
203
204*Attribute references* use the standard syntax used for all attribute references
205in Python: ``obj.name``.  Valid attribute names are all the names that were in
206the class's namespace when the class object was created.  So, if the class
207definition looked like this::
208
209   class MyClass:
n210-       "A simple example class"
n211+       """A simple example class"""
211       i = 12345
212       def f(self):
213           return 'hello world'
214
215then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, returning
216an integer and a function object, respectively. Class attributes can also be
217assigned to, so you can change the value of ``MyClass.i`` by assignment.
218:attr:`__doc__` is also a valid attribute, returning the docstring belonging to
244Of course, the :meth:`__init__` method may have arguments for greater
245flexibility.  In that case, arguments given to the class instantiation operator
246are passed on to :meth:`__init__`.  For example, ::
247
248   >>> class Complex:
249   ...     def __init__(self, realpart, imagpart):
250   ...         self.r = realpart
251   ...         self.i = imagpart
n252-   ... 
n253+   ...
253   >>> x = Complex(3.0, -4.5)
254   >>> x.r, x.i
255   (3.0, -4.5)
256
257
258.. _tut-instanceobjects:
259
260Instance Objects
336is called with this new argument list.
337
338
339.. _tut-remarks:
340
341Random Remarks
342==============
343
n344-.. % [These should perhaps be placed more carefully...]
n345+.. These should perhaps be placed more carefully...
345
346Data attributes override method attributes with the same name; to avoid
347accidental name conflicts, which may cause hard-to-find bugs in large programs,
348it is wise to use some kind of convention that minimizes the chance of
349conflicts.  Possible conventions include capitalizing method names, prefixing
350data attribute names with a small unique string (perhaps just an underscore), or
351using verbs for methods and nouns for data attributes.
352
412definition.  (The class itself is never used as a global scope!)  While one
413rarely encounters a good reason for using global data in a method, there are
414many legitimate uses of the global scope: for one thing, functions and modules
415imported into the global scope can be used by methods, as well as functions and
416classes defined in it.  Usually, the class containing the method is itself
417defined in this global scope, and in the next section we'll find some good
418reasons why a method would want to reference its own class!
419
n421+Each value is an object, and therefore has a *class* (also called its *type*).
422+It is stored as ``object.__class__``.
423+ 
420
421.. _tut-inheritance:
422
423Inheritance
424===========
425
426Of course, a language feature would not be worthy of the name "class" without
427supporting inheritance.  The syntax for a derived class definition looks like
452are resolved as follows: the corresponding class attribute is searched,
453descending down the chain of base classes if necessary, and the method reference
454is valid if this yields a function object.
455
456Derived classes may override methods of their base classes.  Because methods
457have no special privileges when calling other methods of the same object, a
458method of a base class that calls another method defined in the same base class
459may end up calling a method of a derived class that overrides it.  (For C++
n460-programmers: all methods in Python are effectively :keyword:`virtual`.)
n464+programmers: all methods in Python are effectively ``virtual``.)
461
462An overriding method in a derived class may in fact want to extend rather than
463simply replace the base class method of the same name. There is a simple way to
464call the base class method directly: just call ``BaseClassName.methodname(self,
465arguments)``.  This is occasionally useful to clients as well.  (Note that this
466only works if the base class is defined or imported directly in the global
467scope.)
468
n473+Python has two builtin functions that work with inheritance:
474+ 
475+* Use :func:`isinstance` to check an object's type: ``isinstance(obj, int)``
476+  will be ``True`` only if ``obj.__class__`` is :class:`int` or some class
477+  derived from :class:`int`.
478+ 
479+* Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)``
480+  is ``True`` since :class:`bool` is a subclass of :class:`int`.  However,
481+  ``issubclass(unicode, str)`` is ``False`` since :class:`unicode` is not a
482+  subclass of :class:`str` (they only share a common ancestor,
483+  :class:`basestring`).
484+ 
485+ 
469
470.. _tut-multiple:
471
472Multiple Inheritance
473--------------------
474
475Python supports a limited form of multiple inheritance as well.  A class
476definition with multiple base classes looks like this::
477
478   class DerivedClassName(Base1, Base2, Base3):
479       <statement-1>
480       .
481       .
482       .
483       <statement-N>
484
n485-The only rule necessary to explain the semantics is the resolution rule used for
n502+For old-style classes, the only rule is depth-first, left-to-right.  Thus, if an
486-class attribute references.  This is depth-first, left-to-right.  Thus, if an
487attribute is not found in :class:`DerivedClassName`, it is searched in
488:class:`Base1`, then (recursively) in the base classes of :class:`Base1`, and
489only if it is not found there, it is searched in :class:`Base2`, and so on.
490
491(To some people breadth first --- searching :class:`Base2` and :class:`Base3`
492before the base classes of :class:`Base1` --- looks more natural.  However, this
493would require you to know whether a particular attribute of :class:`Base1` is
494actually defined in :class:`Base1` or in one of its base classes before you can
495figure out the consequences of a name conflict with an attribute of
496:class:`Base2`.  The depth-first rule makes no differences between direct and
497inherited attributes of :class:`Base1`.)
498
n499-It is clear that indiscriminate use of multiple inheritance is a maintenance
n515+For :term:`new-style class`\es, the method resolution order changes dynamically
500-nightmare, given the reliance in Python on conventions to avoid accidental name
516+to support cooperative calls to :func:`super`.  This approach is known in some
501-conflicts.  A well-known problem with multiple inheritance is a class derived
517+other multiple-inheritance languages as call-next-method and is more powerful
502-from two classes that happen to have a common base class.  While it is easy
518+than the super call found in single-inheritance languages.
503-enough to figure out what happens in this case (the instance will have a single
504-copy of "instance variables" or data attributes used by the common base class),
505-it is not clear that these semantics are in any way useful.
506
n507-.. % % XXX Add rules for new-style MRO?
n520+With new-style classes, dynamic ordering is necessary because all  cases of
521+multiple inheritance exhibit one or more diamond relationships (where one at
522+least one of the parent classes can be accessed through multiple paths from the
523+bottommost class).  For example, all new-style classes inherit from
524+:class:`object`, so any case of multiple inheritance provides more than one path
525+to reach :class:`object`.  To keep the base classes from being accessed more
526+than once, the dynamic algorithm linearizes the search order in a way that
527+preserves the left-to-right ordering specified in each class, that calls each
528+parent only once, and that is monotonic (meaning that a class can be subclassed
529+without affecting the precedence order of its parents).  Taken together, these
530+properties make it possible to design reliable and extensible classes with
531+multiple inheritance.  For more detail, see
532+http://www.python.org/download/releases/2.3/mro/.
508
509
510.. _tut-private:
511
512Private Variables
513=================
514
515There is limited support for class-private identifiers.  Any identifier of the
561   john.salary = 1000
562
563A piece of Python code that expects a particular abstract data type can often be
564passed a class that emulates the methods of that data type instead.  For
565instance, if you have a function that formats some data from a file object, you
566can define a class with methods :meth:`read` and :meth:`readline` that get the
567data from a string buffer instead, and pass it as an argument.
568
n569-.. % (Unfortunately, this
n594+.. (Unfortunately, this technique has its limitations: a class can't define
570-.. % technique has its limitations: a class can't define operations that
571-.. % are accessed by special syntax such as sequence subscripting or
595+   operations that are accessed by special syntax such as sequence subscripting
572-.. % arithmetic operators, and assigning such a ``pseudo-file'' to
596+   or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will
573-.. % \code{sys.stdin} will not cause the interpreter to read further input
597+   not cause the interpreter to read further input from it.)
574-.. % from it.)
575
576Instance method objects have attributes, too: ``m.im_self`` is the instance
577object with the method :meth:`m`, and ``m.im_func`` is the function object
578corresponding to the method.
579
580
581.. _tut-exceptionclasses:
582
698   s
699
700
701.. _tut-generators:
702
703Generators
704==========
705
n706-Generators are a simple and powerful tool for creating iterators.  They are
n729+:term:`Generator`\s are a simple and powerful tool for creating iterators.  They
707-written like regular functions but use the :keyword:`yield` statement whenever
730+are written like regular functions but use the :keyword:`yield` statement
708-they want to return data.  Each time :meth:`next` is called, the generator
731+whenever they want to return data.  Each time :meth:`next` is called, the
709-resumes where it left-off (it remembers all the data values and which statement
732+generator resumes where it left-off (it remembers all the data values and which
710-was last executed).  An example shows that generators can be trivially easy to
733+statement was last executed).  An example shows that generators can be trivially
711-create::
734+easy to create::
712
713   def reverse(data):
714       for index in range(len(data)-1, -1, -1):
715           yield data[index]
716
717   >>> for char in reverse('golf'):
718   ...     print char
719   ...
720   f
721   l
722   o
t723-   g    
t746+   g
724
725Anything that can be done with generators can also be done with class based
726iterators as described in the previous section.  What makes generators so
727compact is that the :meth:`__iter__` and :meth:`next` methods are created
728automatically.
729
730Another key feature is that the local variables and execution state are
731automatically saved between calls.  This made the function easier to write and
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op