diff options
Diffstat (limited to 'Doc/tutorial')
| -rw-r--r-- | Doc/tutorial/classes.rst | 12 | ||||
| -rw-r--r-- | Doc/tutorial/errors.rst | 38 | ||||
| -rw-r--r-- | Doc/tutorial/inputoutput.rst | 17 | ||||
| -rw-r--r-- | Doc/tutorial/introduction.rst | 14 | ||||
| -rw-r--r-- | Doc/tutorial/modules.rst | 22 |
5 files changed, 56 insertions, 47 deletions
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst index 9a01f3a..1488329 100644 --- a/Doc/tutorial/classes.rst +++ b/Doc/tutorial/classes.rst @@ -50,8 +50,8 @@ need for two different argument passing mechanisms as in Pascal. .. _tut-scopes: -Python Scopes and Name Spaces -============================= +Python Scopes and Namespaces +============================ Before introducing classes, I first have to tell you something about Python's scope rules. Class definitions play some neat tricks with namespaces, and you @@ -86,7 +86,7 @@ attributes is possible. Module attributes are writable: you can write :keyword:`del` statement. For example, ``del modname.the_answer`` will remove the attribute :attr:`the_answer` from the object named by ``modname``. -Name spaces are created at different moments and have different lifetimes. The +Namespaces are created at different moments and have different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last @@ -331,9 +331,9 @@ data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called -with an argument list, it is unpacked again, a new argument list is constructed -from the instance object and the original argument list, and the function object -is called with this new argument list. +with an argument list, a new argument list is constructed from the instance +object and the argument list, and the function object is called with this new +argument list. .. _tut-remarks: diff --git a/Doc/tutorial/errors.rst b/Doc/tutorial/errors.rst index d547ef7..a0069f5 100644 --- a/Doc/tutorial/errors.rst +++ b/Doc/tutorial/errors.rst @@ -165,14 +165,11 @@ exception type. The except clause may specify a variable after the exception name (or tuple). The variable is bound to an exception instance with the arguments stored in ``instance.args``. For convenience, the exception instance defines -:meth:`__getitem__` and :meth:`__str__` so the arguments can be accessed or -printed directly without having to reference ``.args``. +:meth:`__str__` so the arguments can be printed directly without having to +reference ``.args``. -But use of ``.args`` is discouraged. Instead, the preferred use is to pass a -single argument to an exception (which can be a tuple if multiple arguments are -needed) and have it bound to the ``message`` attribute. One may also -instantiate an exception first before raising it and add any attributes to it as -desired. :: +One may also instantiate an exception first before raising it and add any +attributes to it as desired. :: >>> try: ... raise Exception('spam', 'eggs') @@ -248,9 +245,10 @@ re-raise the exception:: User-defined Exceptions ======================= -Programs may name their own exceptions by creating a new exception class. -Exceptions should typically be derived from the :exc:`Exception` class, either -directly or indirectly. For example:: +Programs may name their own exceptions by creating a new exception class (see +:ref:`tut-classes` for more about Python classes). Exceptions should typically +be derived from the :exc:`Exception` class, either directly or indirectly. For +example:: >>> class MyError(Exception): ... def __init__(self, value): @@ -288,28 +286,28 @@ to create specific exception classes for different error conditions:: """Exception raised for errors in the input. Attributes: - expression -- input expression in which the error occurred - message -- explanation of the error + expr -- input expression in which the error occurred + msg -- explanation of the error """ - def __init__(self, expression, message): - self.expression = expression - self.message = message + def __init__(self, expr, msg): + self.expr = expr + self.msg = msg class TransitionError(Error): """Raised when an operation attempts a state transition that's not allowed. Attributes: - previous -- state at beginning of transition + prev -- state at beginning of transition next -- attempted new state - message -- explanation of why the specific transition is not allowed + msg -- explanation of why the specific transition is not allowed """ - def __init__(self, previous, next, message): - self.previous = previous + def __init__(self, prev, next, msg): + self.prev = prev self.next = next - self.message = message + self.msg = msg Most exceptions are defined with names that end in "Error," similar to the naming of the standard exceptions. diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst index 9352f40..0259749 100644 --- a/Doc/tutorial/inputoutput.rst +++ b/Doc/tutorial/inputoutput.rst @@ -123,11 +123,11 @@ with zeros. It understands about plus and minus signs:: Basic usage of the :meth:`str.format` method looks like this:: - >>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni') + >>> print 'We are the {} who say "{}!"'.format('knights', 'Ni') We are the knights who say "Ni!" The brackets and characters within them (called format fields) are replaced with -the objects passed into the :meth:`~str.format` method. The number in the +the objects passed into the :meth:`~str.format` method. A number in the brackets refers to the position of the object passed into the :meth:`~str.format` method. :: @@ -149,6 +149,15 @@ Positional and keyword arguments can be arbitrarily combined:: ... other='Georg') The story of Bill, Manfred, and Georg. +``'!s'`` (apply :func:`str`) and ``'!r'`` (apply :func:`repr`) can be used to +convert the value before it is formatted. :: + + >>> import math + >>> print 'The value of PI is approximately {}.'.format(math.pi) + The value of PI is approximately 3.14159265359. + >>> print 'The value of PI is approximately {!r}.'.format(math.pi) + The value of PI is approximately 3.141592653589793. + An optional ``':'`` and format specifier can follow the field name. This allows greater control over how the value is formatted. The following example truncates Pi to three places after the decimal. @@ -239,8 +248,8 @@ writing. The *mode* argument is optional; ``'r'`` will be assumed if it's omitted. On Windows, ``'b'`` appended to the mode opens the file in binary mode, so there -are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Windows makes a -distinction between text and binary files; the end-of-line characters in text +are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Python on Windows makes +a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it'll corrupt binary data like that in :file:`JPEG` or :file:`EXE` files. Be diff --git a/Doc/tutorial/introduction.rst b/Doc/tutorial/introduction.rst index 23ff522..1d67ed3 100644 --- a/Doc/tutorial/introduction.rst +++ b/Doc/tutorial/introduction.rst @@ -138,7 +138,6 @@ its magnitude (as a float) or ``z.real`` to get its real part. :: 4.0 >>> abs(a) # sqrt(a.real**2 + a.imag**2) 5.0 - >>> In interactive mode, the last printed expression is assigned to the variable ``_``. This means that when you are using Python as a desk calculator, it is @@ -152,7 +151,6 @@ somewhat easier to continue calculations, for example:: 113.0625 >>> round(_, 2) 113.06 - >>> This variable should be treated as read-only by the user. Don't explicitly assign a value to it --- you would create an independent local variable with the @@ -193,7 +191,9 @@ next line is a logical continuation of the line:: Note that newlines still need to be embedded in the string using ``\n``; the newline following the trailing backslash is discarded. This example would print -the following:: +the following: + +.. code-block:: text This is a rather long string containing several lines of text just as you would do in C. @@ -209,7 +209,9 @@ they will be included in the string. :: -H hostname Hostname to connect to """ -produces the following output:: +produces the following output: + +.. code-block:: text Usage: thingy [OPTIONS] -h Display this usage message @@ -224,7 +226,9 @@ in the source, are both included in the string as data. Thus, the example:: print hello -would print:: +would print: + +.. code-block:: text This is a rather long string containing\n\ several lines of text much as you would do in C. diff --git a/Doc/tutorial/modules.rst b/Doc/tutorial/modules.rst index d1f9cc3..48858f3 100644 --- a/Doc/tutorial/modules.rst +++ b/Doc/tutorial/modules.rst @@ -103,6 +103,10 @@ There is even a variant to import all names that a module defines:: This imports all names except those beginning with an underscore (``_``). +Note that in general the practice of importing ``*`` from a module or package is +frowned upon, since it often causes poorly readable code. However, it is okay to +use it to save typing in interactive sessions. + .. note:: For efficiency reasons, each module is only imported once per interpreter @@ -443,14 +447,9 @@ Importing \* From a Package Now what happens when the user writes ``from sound.effects import *``? Ideally, one would hope that this somehow goes out to the filesystem, finds which -submodules are present in the package, and imports them all. Unfortunately, -this operation does not work very well on Windows platforms, where the -filesystem does not always have accurate information about the case of a -filename. On these platforms, there is no guaranteed way to know whether a file -:file:`ECHO.PY` should be imported as a module :mod:`echo`, :mod:`Echo` or -:mod:`ECHO`. (For example, Windows 95 has the annoying practice of showing all -file names with a capitalized first letter.) The DOS 8+3 filename restriction -adds another interesting problem for long module names. +submodules are present in the package, and imports them all. This could take a +long time and importing sub-modules might have unwanted side-effects that should +only happen when the sub-module is explicitly imported. The only solution is for the package author to provide an explicit index of the package. The :keyword:`import` statement uses the following convention: if a package's @@ -485,10 +484,9 @@ current namespace because they are defined in the :mod:`sound.effects` package when the ``from...import`` statement is executed. (This also works when ``__all__`` is defined.) -Note that in general the practice of importing ``*`` from a module or package is -frowned upon, since it often causes poorly readable code. However, it is okay to -use it to save typing in interactive sessions, and certain modules are designed -to export only names that follow certain patterns. +Although certain modules are designed to export only names that follow certain +patterns when you use ``import *``, it is still considered bad practise in +production code. Remember, there is nothing wrong with using ``from Package import specific_submodule``! In fact, this is the recommended notation unless the |
