| It is important to realize that scopes are determined textually: the global |
| scope of a function defined in a module is that module's namespace, no matter |
| from where or by what alias the function is called. On the other hand, the |
| actual search for names is done dynamically, at run time --- however, the |
| language definition is evolving towards static name resolution, at "compile" |
| time, so don't rely on dynamic name resolution! (In fact, local variables are |
| already determined statically.) |
| |
n | A special quirk of Python is that assignments always go into the innermost |
n | A special quirk of Python is that -- if no :keyword:`global` |
| statement is in effect -- assignments to names always go |
| scope. Assignments do not copy data --- they just bind names to objects. The |
| into the innermost scope. Assignments do not copy data --- they just bind names |
| same is true for deletions: the statement ``del x`` removes the binding of ``x`` |
| to objects. The same is true for deletions: the statement ``del x`` removes the |
| from the namespace referenced by the local scope. In fact, all operations that |
| binding of ``x`` from the namespace referenced by the local scope. In fact, all |
| introduce new names use the local scope: in particular, import statements and |
| operations that introduce new names use the local scope: in particular, import |
| function definitions bind the module or function name in the local scope. (The |
| statements and function definitions bind the module or function name in the |
| :keyword:`global` statement can be used to indicate that particular variables |
| local scope. (The :keyword:`global` statement can be used to indicate that |
| live in the global scope.) |
| particular variables live in the global scope.) |
| |
| |
| .. _tut-firstclasses: |
| |
| A First Look at Classes |
| ======================= |
| |
| Classes introduce a little bit of new syntax, three new object types, and some |
| are resolved as follows: the corresponding class attribute is searched, |
| descending down the chain of base classes if necessary, and the method reference |
| is valid if this yields a function object. |
| |
| Derived classes may override methods of their base classes. Because methods |
| have no special privileges when calling other methods of the same object, a |
| method of a base class that calls another method defined in the same base class |
| may end up calling a method of a derived class that overrides it. (For C++ |
n | programmers: all methods in Python are effectively :keyword:`virtual`.) |
n | programmers: all methods in Python are effectively ``virtual``.) |
| |
| An overriding method in a derived class may in fact want to extend rather than |
| simply replace the base class method of the same name. There is a simple way to |
| call the base class method directly: just call ``BaseClassName.methodname(self, |
| arguments)``. This is occasionally useful to clients as well. (Note that this |
| only works if the base class is defined or imported directly in the global |
| scope.) |
| |
n | Python has two builtin functions that work with inheritance: |
| |
| * Use :func:`isinstance` to check an object's type: ``isinstance(obj, int)`` |
| will be ``True`` only if ``obj.__class__`` is :class:`int` or some class |
| derived from :class:`int`. |
| |
| * Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)`` |
| is ``True`` since :class:`bool` is a subclass of :class:`int`. However, |
| ``issubclass(unicode, str)`` is ``False`` since :class:`unicode` is not a |
| subclass of :class:`str` (they only share a common ancestor, |
| :class:`basestring`). |
| |
| |
| |
| .. _tut-multiple: |
| |
| Multiple Inheritance |
| -------------------- |
| |
| Python supports a limited form of multiple inheritance as well. A class |
| definition with multiple base classes looks like this:: |
| |
| class DerivedClassName(Base1, Base2, Base3): |
| <statement-1> |
| . |
| . |
| . |
| <statement-N> |
| |
n | The only rule necessary to explain the semantics is the resolution rule used for |
n | For old-style classes, the only rule is depth-first, left-to-right. Thus, if an |
| class attribute references. This 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. |
| |
| (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`.) |
| |
n | It is clear that indiscriminate use of multiple inheritance is a maintenance |
n | For :term:`new-style class`\es, the method resolution order changes dynamically |
| nightmare, given the reliance in Python on conventions to avoid accidental name |
| to support cooperative calls to :func:`super`. This approach is known in some |
| conflicts. A well-known problem with multiple inheritance is a class derived |
| other multiple-inheritance languages as call-next-method and is more powerful |
| from two classes that happen to have a common base class. While it is easy |
| than the super call found in single-inheritance languages. |
| enough to figure out what happens in this case (the instance will have a single |
| copy of "instance variables" or data attributes used by the common base class), |
| it is not clear that these semantics are in any way useful. |
| |
n | .. % % XXX Add rules for new-style MRO? |
n | 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 |
| http://www.python.org/download/releases/2.3/mro/. |
| |
| |
| .. _tut-private: |
| |
| Private Variables |
| ================= |
| |
| There is limited support for class-private identifiers. Any identifier of the |
| john.salary = 1000 |
| |
| A piece of Python code that expects a particular abstract data type can often be |
| passed a class that emulates the methods of that data type instead. For |
| instance, if you have a function that formats some data from a file object, you |
| can define a class with methods :meth:`read` and :meth:`readline` that get the |
| data from a string buffer instead, and pass it as an argument. |
| |
n | .. % (Unfortunately, this |
n | .. (Unfortunately, this technique has its limitations: a class can't define |
| .. % technique has its limitations: a class can't define operations that |
| .. % are accessed by special syntax such as sequence subscripting or |
| operations that are accessed by special syntax such as sequence subscripting |
| .. % arithmetic operators, and assigning such a ``pseudo-file'' to |
| or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will |
| .. % \code{sys.stdin} will not cause the interpreter to read further input |
| not cause the interpreter to read further input from it.) |
| .. % from it.) |
| |
| Instance method objects have attributes, too: ``m.im_self`` is the instance |
| object with the method :meth:`m`, and ``m.im_func`` is the function object |
| corresponding to the method. |
| |
| |
| .. _tut-exceptionclasses: |
| |
| s |
| |
| |
| .. _tut-generators: |
| |
| Generators |
| ========== |
| |
n | Generators are a simple and powerful tool for creating iterators. They are |
n | :term:`Generator`\s are a simple and powerful tool for creating iterators. They |
| written like regular functions but use the :keyword:`yield` statement whenever |
| are written like regular functions but use the :keyword:`yield` statement |
| they want to return data. Each time :meth:`next` is called, the generator |
| whenever they want to return data. Each time :meth:`next` is called, the |
| resumes where it left-off (it remembers all the data values and which statement |
| generator resumes where it left-off (it remembers all the data values and which |
| was last executed). An example shows that generators can be trivially easy to |
| statement was last executed). An example shows that generators can be trivially |
| create:: |
| easy to create:: |
| |
| def reverse(data): |
| for index in range(len(data)-1, -1, -1): |
| yield data[index] |
| |
| >>> for char in reverse('golf'): |
| ... print char |
| ... |
| f |
| l |
| o |
t | g |
t | g |
| |
| Anything that can be done with generators can also be done with class based |
| iterators as described in the previous section. What makes generators so |
| compact is that the :meth:`__iter__` and :meth:`next` methods are created |
| automatically. |
| |
| Another key feature is that the local variables and execution state are |
| automatically saved between calls. This made the function easier to write and |