Changeset 391 for python/trunk/Doc/library/functions.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/functions.rst
r2 r391 7 7 The Python interpreter has a number of functions built into it that are always 8 8 available. They are listed here in alphabetical order. 9 10 =================== ================= ================== ================= ==================== 11 .. .. Built-in Functions .. .. 12 =================== ================= ================== ================= ==================== 13 :func:`abs` :func:`divmod` :func:`input` :func:`open` :func:`staticmethod` 14 :func:`all` :func:`enumerate` :func:`int` :func:`ord` :func:`str` 15 :func:`any` :func:`eval` :func:`isinstance` :func:`pow` :func:`sum` 16 :func:`basestring` :func:`execfile` :func:`issubclass` :func:`print` :func:`super` 17 :func:`bin` :func:`file` :func:`iter` :func:`property` :func:`tuple` 18 :func:`bool` :func:`filter` :func:`len` :func:`range` :func:`type` 19 :func:`bytearray` :func:`float` :func:`list` :func:`raw_input` :func:`unichr` 20 :func:`callable` :func:`format` :func:`locals` :func:`reduce` :func:`unicode` 21 :func:`chr` |func-frozenset|_ :func:`long` :func:`reload` :func:`vars` 22 :func:`classmethod` :func:`getattr` :func:`map` |func-repr|_ :func:`xrange` 23 :func:`cmp` :func:`globals` :func:`max` :func:`reversed` :func:`zip` 24 :func:`compile` :func:`hasattr` |func-memoryview|_ :func:`round` :func:`__import__` 25 :func:`complex` :func:`hash` :func:`min` |func-set|_ :func:`apply` 26 :func:`delattr` :func:`help` :func:`next` :func:`setattr` :func:`buffer` 27 |func-dict|_ :func:`hex` :func:`object` :func:`slice` :func:`coerce` 28 :func:`dir` :func:`id` :func:`oct` :func:`sorted` :func:`intern` 29 =================== ================= ================== ================= ==================== 30 31 .. using :func:`dict` would create a link to another page, so local targets are 32 used, with replacement texts to make the output in the table consistent 33 34 .. |func-dict| replace:: ``dict()`` 35 .. |func-frozenset| replace:: ``frozenset()`` 36 .. |func-memoryview| replace:: ``memoryview()`` 37 .. |func-repr| replace:: ``repr()`` 38 .. |func-set| replace:: ``set()`` 9 39 10 40 … … 77 107 .. versionchanged:: 2.3 78 108 If no argument is given, this function returns :const:`False`. 109 110 111 .. function:: bytearray([source[, encoding[, errors]]]) 112 113 Return a new array of bytes. The :class:`bytearray` type is a mutable 114 sequence of integers in the range 0 <= x < 256. It has most of the usual 115 methods of mutable sequences, described in :ref:`typesseq-mutable`, as well 116 as most methods that the :class:`str` type has, see :ref:`string-methods`. 117 118 The optional *source* parameter can be used to initialize the array in a few 119 different ways: 120 121 * If it is a *string*, you must also give the *encoding* (and optionally, 122 *errors*) parameters; :func:`bytearray` then converts the string to 123 bytes using :meth:`str.encode`. 124 125 * If it is an *integer*, the array will have that size and will be 126 initialized with null bytes. 127 128 * If it is an object conforming to the *buffer* interface, a read-only buffer 129 of the object will be used to initialize the bytes array. 130 131 * If it is an *iterable*, it must be an iterable of integers in the range 132 ``0 <= x < 256``, which are used as the initial contents of the array. 133 134 Without an argument, an array of size 0 is created. 135 136 .. versionadded:: 2.6 79 137 80 138 … … 106 164 idiom:: 107 165 108 class C :166 class C(object): 109 167 @classmethod 110 def f(cls, arg1, arg2, ...): ... 168 def f(cls, arg1, arg2, ...): 169 ... 111 170 112 171 The ``@classmethod`` form is a function :term:`decorator` -- see the description … … 141 200 Compile the *source* into a code or AST object. Code objects can be executed 142 201 by an :keyword:`exec` statement or evaluated by a call to :func:`eval`. 143 *source* can either be a string or an AST object. Refer to the :mod:`ast` 144 module documentation for information on how to work with AST objects. 202 *source* can either be a Unicode string, a *Latin-1* encoded string or an 203 AST object. 204 Refer to the :mod:`ast` module documentation for information on how to work 205 with AST objects. 145 206 146 207 The *filename* argument should give the file from which the code was read; … … 166 227 Future statements are specified by bits which can be bitwise ORed together to 167 228 specify multiple statements. The bitfield required to specify a given feature 168 can be found as the :attr:` compiler_flag` attribute on the :class:`_Feature`169 instance in the :mod:`__future__` module.229 can be found as the :attr:`~__future__._Feature.compiler_flag` attribute on 230 the :class:`~__future__._Feature` instance in the :mod:`__future__` module. 170 231 171 232 This function raises :exc:`SyntaxError` if the compiled source is invalid, … … 174 235 .. note:: 175 236 176 When compiling a string with multi-line statements, line endings must be 177 represented by a single newline character (``'\n'``), and the input must 178 be terminated by at least one newline character. If line endings are 179 represented by ``'\r\n'``, use :meth:`str.replace` to change them into 180 ``'\n'``. 237 When compiling a string with multi-line code in ``'single'`` or 238 ``'eval'`` mode, input must be terminated by at least one newline 239 character. This is to facilitate detection of incomplete and complete 240 statements in the :mod:`code` module. 181 241 182 242 .. versionchanged:: 2.3 … … 185 245 .. versionchanged:: 2.6 186 246 Support for compiling AST objects. 247 248 .. versionchanged:: 2.7 249 Allowed use of Windows and Mac newlines. Also input in ``'exec'`` mode 250 does not have to end in a newline anymore. 187 251 188 252 … … 197 261 :func:`long` and :func:`float`. If both arguments are omitted, returns ``0j``. 198 262 263 .. note:: 264 265 When converting from a string, the string must not contain whitespace 266 around the central ``+`` or ``-`` operator. For example, 267 ``complex('1+2j')`` is fine, but ``complex('1 + 2j')`` raises 268 :exc:`ValueError`. 269 199 270 The complex type is described in :ref:`typesnumeric`. 200 271 … … 208 279 209 280 210 .. function:: dict([arg]) 281 .. _func-dict: 282 .. function:: dict(**kwarg) 283 dict(mapping, **kwarg) 284 dict(iterable, **kwarg) 211 285 :noindex: 212 286 213 Create a new data dictionary, optionally with items taken from *arg*. 214 The dictionary type is described in :ref:`typesmapping`. 215 216 For other containers see the built in :class:`list`, :class:`set`, and 217 :class:`tuple` classes, and the :mod:`collections` module. 287 Create a new dictionary. The :class:`dict` object is the dictionary class. 288 See :class:`dict` and :ref:`typesmapping` for documentation about this 289 class. 290 291 For other containers see the built-in :class:`list`, :class:`set`, and 292 :class:`tuple` classes, as well as the :mod:`collections` module. 218 293 219 294 … … 250 325 251 326 >>> import struct 252 >>> dir() # doctest: +SKIP327 >>> dir() # show the names in the module namespace 253 328 ['__builtins__', '__doc__', '__name__', 'struct'] 254 >>> dir(struct) # doctest: +NORMALIZE_WHITESPACE329 >>> dir(struct) # show the names in the struct module 255 330 ['Struct', '__builtins__', '__doc__', '__file__', '__name__', 256 331 '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 257 332 'unpack', 'unpack_from'] 258 >>> class Foo(object): 259 ... def __dir__(self): 260 ... return ["kan", "ga", "roo"] 261 ... 262 >>> f = Foo() 263 >>> dir(f) 264 ['ga', 'kan', 'roo'] 333 >>> class Shape(object): 334 def __dir__(self): 335 return ['area', 'perimeter', 'location'] 336 >>> s = Shape() 337 >>> dir(s) 338 ['area', 'perimeter', 'location'] 265 339 266 340 .. note:: … … 288 362 289 363 290 .. function:: enumerate(sequence [, start=0])364 .. function:: enumerate(sequence, start=0) 291 365 292 366 Return an enumerate object. *sequence* must be a sequence, an … … 294 368 :meth:`!next` method of the iterator returned by :func:`enumerate` returns a 295 369 tuple containing a count (from *start* which defaults to 0) and the 296 corresponding value obtained from iterating over *iterable*. 297 :func:`enumerate` is useful for obtaining an indexed series: ``(0, seq[0])``, 298 ``(1, seq[1])``, ``(2, seq[2])``, .... For example: 299 300 >>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']): 301 ... print i, season 302 0 Spring 303 1 Summer 304 2 Fall 305 3 Winter 370 values obtained from iterating over *sequence*:: 371 372 >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] 373 >>> list(enumerate(seasons)) 374 [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] 375 >>> list(enumerate(seasons, start=1)) 376 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] 377 378 Equivalent to:: 379 380 def enumerate(sequence, start=0): 381 n = start 382 for elem in sequence: 383 yield n, elem 384 n += 1 306 385 307 386 .. versionadded:: 2.3 308 .. version added:: 2.6309 The *start* parameter .387 .. versionchanged:: 2.6 388 The *start* parameter was added. 310 389 311 390 312 391 .. function:: eval(expression[, globals[, locals]]) 313 392 314 The arguments are a string and optional globals and locals. If provided,315 *globals* must be a dictionary. If provided, *locals* can be any mapping316 object.393 The arguments are a Unicode or *Latin-1* encoded string and optional 394 globals and locals. If provided, *globals* must be a dictionary. 395 If provided, *locals* can be any mapping object. 317 396 318 397 .. versionchanged:: 2.4 … … 337 416 those created by :func:`compile`). In this case pass a code object instead 338 417 of a string. If the code object has been compiled with ``'exec'`` as the 339 * kind* argument, :func:`eval`\'s return value will be ``None``.418 *mode* argument, :func:`eval`\'s return value will be ``None``. 340 419 341 420 Hints: dynamic execution of statements is supported by the :keyword:`exec` … … 345 424 useful to pass around for use by :func:`eval` or :func:`execfile`. 346 425 426 See :func:`ast.literal_eval` for a function that can safely evaluate strings 427 with expressions containing only literals. 428 347 429 348 430 .. function:: execfile(filename[, globals[, locals]]) … … 356 438 and evaluated as a sequence of Python statements (similarly to a module) using 357 439 the *globals* and *locals* dictionaries as global and local namespace. If 358 provided, *locals* can be any mapping object. 440 provided, *locals* can be any mapping object. Remember that at module level, 441 globals and locals are the same dictionary. If two separate objects are 442 passed as *globals* and *locals*, the code will be executed as if it were 443 embedded in a class definition. 359 444 360 445 .. versionchanged:: 2.4 … … 374 459 375 460 376 .. function:: file( filename[, mode[, bufsize]])461 .. function:: file(name[, mode[, buffering]]) 377 462 378 463 Constructor function for the :class:`file` type, described further in section … … 400 485 in iterable if item]`` if function is ``None``. 401 486 402 See :func:`itertools.filterfalse` for the complementary function that returns 403 elements of *iterable* for which *function* returns false. 487 See :func:`itertools.ifilter` and :func:`itertools.ifilterfalse` for iterator 488 versions of this function, including a variation that filters for elements 489 where the *function* returns false. 404 490 405 491 … … 448 534 449 535 536 .. _func-frozenset: 450 537 .. function:: frozenset([iterable]) 451 538 :noindex: 452 539 453 Return a frozenset object, optionally with elements taken from *iterable*. 454 The frozenset type is described in :ref:`types-set`. 455 456 For other containers see the built in :class:`dict`, :class:`list`, and 457 :class:`tuple` classes, and the :mod:`collections` module. 540 Return a new :class:`frozenset` object, optionally with elements taken from 541 *iterable*. ``frozenset`` is a built-in class. See :class:`frozenset` and 542 :ref:`types-set` for documentation about this class. 543 544 For other containers see the built-in :class:`set`, :class:`list`, 545 :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections` 546 module. 458 547 459 548 .. versionadded:: 2.4 … … 462 551 .. function:: getattr(object, name[, default]) 463 552 464 Return the value of the named attribute dof *object*. *name* must be a string.553 Return the value of the named attribute of *object*. *name* must be a string. 465 554 If the string is the name of one of the object's attributes, the result is the 466 555 value of that attribute. For example, ``getattr(x, 'foobar')`` is equivalent to … … 527 616 value. 528 617 529 .. impl-detail:: This is the address of the object .618 .. impl-detail:: This is the address of the object in memory. 530 619 531 620 … … 534 623 Equivalent to ``eval(raw_input(prompt))``. 535 624 536 .. warning:: 537 538 This function is not safe from user errors! It expects a valid Python 539 expression as input; if the input is not syntactically valid, a 540 :exc:`SyntaxError` will be raised. Other exceptions may be raised if there is an 541 error during evaluation. (On the other hand, sometimes this is exactly what you 542 need when writing a quick script for expert use.) 625 This function does not catch user errors. If the input is not syntactically 626 valid, a :exc:`SyntaxError` will be raised. Other exceptions may be raised if 627 there is an error during evaluation. 543 628 544 629 If the :mod:`readline` module was loaded, then :func:`input` will use it to … … 548 633 549 634 550 .. function:: int([x[, base]]) 551 552 Convert a string or number to a plain integer. If the argument is a string, 553 it must contain a possibly signed decimal number representable as a Python 554 integer, possibly embedded in whitespace. The *base* parameter gives the 555 base for the conversion (which is 10 by default) and may be any integer in 556 the range [2, 36], or zero. If *base* is zero, the proper radix is 557 determined based on the contents of string; the interpretation is the same as 558 for integer literals. (See :ref:`numbers`.) If *base* is specified and *x* 559 is not a string, :exc:`TypeError` is raised. Otherwise, the argument may be a 560 plain or long integer or a floating point number. Conversion of floating 561 point numbers to integers truncates (towards zero). If the argument is 562 outside the integer range a long object will be returned instead. If no 563 arguments are given, returns ``0``. 635 .. function:: int(x=0) 636 int(x, base=10) 637 638 Convert a number or string *x* to an integer, or return ``0`` if no 639 arguments are given. If *x* is a number, it can be a plain integer, a long 640 integer, or a floating point number. If *x* is floating point, the conversion 641 truncates towards zero. If the argument is outside the integer range, the 642 function returns a long object instead. 643 644 If *x* is not a number or if *base* is given, then *x* must be a string or 645 Unicode object representing an :ref:`integer literal <integers>` in radix 646 *base*. Optionally, the literal can be 647 preceded by ``+`` or ``-`` (with no space in between) and surrounded by 648 whitespace. A base-n literal consists of the digits 0 to n-1, with ``a`` 649 to ``z`` (or ``A`` to ``Z``) having 650 values 10 to 35. The default *base* is 10. The allowed values are 0 and 2-36. 651 Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``, 652 ``0o``/``0O``/``0``, or ``0x``/``0X``, as with integer literals in code. 653 Base 0 means to interpret the string exactly as an integer literal, so that 654 the actual base is 2, 8, 10, or 16. 564 655 565 656 The integer type is described in :ref:`typesnumeric`. … … 569 660 570 661 Return true if the *object* argument is an instance of the *classinfo* argument, 571 or of a (direct or indirect) subclass thereof. Also return true if *classinfo* 662 or of a (direct, indirect or :term:`virtual <abstract base class>`) subclass 663 thereof. Also return true if *classinfo* 572 664 is a type object (new-style class) and *object* is an object of that type or of 573 a (direct or indirect) subclass thereof. If *object* is not a class instance or 665 a (direct, indirect or :term:`virtual <abstract base class>`) subclass 666 thereof. If *object* is not a class instance or 574 667 an object of the given type, the function always returns false. If *classinfo* 575 668 is neither a class object nor a type object, it may be a tuple of class or type … … 584 677 .. function:: issubclass(class, classinfo) 585 678 586 Return true if *class* is a subclass (direct or indirect) of *classinfo*. A 679 Return true if *class* is a subclass (direct, indirect or :term:`virtual 680 <abstract base class>`) of *classinfo*. A 587 681 class is considered a subclass of itself. *classinfo* may be a tuple of class 588 682 objects, in which case every entry in *classinfo* will be checked. In any other … … 608 702 One useful application of the second form of :func:`iter` is to read lines of 609 703 a file until a certain line is reached. The following example reads a file 610 until ``"STOP"`` is reached:::611 612 with open( "mydata.txt") as fp:613 for line in iter(fp.readline, "STOP"):704 until the :meth:`~io.TextIOBase.readline` method returns an empty string:: 705 706 with open('mydata.txt') as fp: 707 for line in iter(fp.readline, ''): 614 708 process_line(line) 615 709 … … 649 743 650 744 651 .. function:: long([x[, base]]) 745 .. function:: long(x=0) 746 long(x, base=10) 652 747 653 748 Convert a string or number to a long integer. If the argument is a string, it … … 675 770 676 771 677 .. function:: max(iterable[, args...][key]) 678 679 With a single argument *iterable*, return the largest item of a non-empty 680 iterable (such as a string, tuple or list). With more than one argument, return 681 the largest of the arguments. 772 .. function:: max(iterable[, key]) 773 max(arg1, arg2, *args[, key]) 774 775 Return the largest item in an iterable or the largest of two or more 776 arguments. 777 778 If one positional argument is provided, *iterable* must be a non-empty 779 iterable (such as a non-empty string, tuple or list). The largest item 780 in the iterable is returned. If two or more positional arguments are 781 provided, the largest of the positional arguments is returned. 682 782 683 783 The optional *key* argument specifies a one-argument ordering function like that … … 688 788 Added support for the optional *key* argument. 689 789 690 691 .. function:: min(iterable[, args...][key]) 692 693 With a single argument *iterable*, return the smallest item of a non-empty 694 iterable (such as a string, tuple or list). With more than one argument, return 695 the smallest of the arguments. 790 .. _func-memoryview: 791 .. function:: memoryview(obj) 792 :noindex: 793 794 Return a "memory view" object created from the given argument. See 795 :ref:`typememoryview` for more information. 796 797 798 .. function:: min(iterable[, key]) 799 min(arg1, arg2, *args[, key]) 800 801 Return the smallest item in an iterable or the smallest of two or more 802 arguments. 803 804 If one positional argument is provided, *iterable* must be a non-empty 805 iterable (such as a non-empty string, tuple or list). The smallest item 806 in the iterable is returned. If two or more positional arguments are 807 provided, the smallest of the positional arguments is returned. 696 808 697 809 The optional *key* argument specifies a one-argument ordering function like that … … 734 846 735 847 736 .. function:: open( filename[, mode[, bufsize]])848 .. function:: open(name[, mode[, buffering]]) 737 849 738 850 Open a file, returning an object of the :class:`file` type described in … … 741 853 :func:`open` instead of invoking the :class:`file` constructor directly. 742 854 743 The first two arguments are the same as for ``stdio``'s :c func:`fopen`:744 * filename* is the file name to be opened, and *mode* is a string indicating how855 The first two arguments are the same as for ``stdio``'s :c:func:`fopen`: 856 *name* is the file name to be opened, and *mode* is a string indicating how 745 857 the file is to be opened. 746 858 … … 763 875 single: I/O control; buffering 764 876 765 The optional *buf size* argument specifies the file's desired buffer size: 0877 The optional *buffering* argument specifies the file's desired buffer size: 0 766 878 means unbuffered, 1 means line buffered, any other positive value means use a 767 buffer of (approximately) that size . A negative *bufsize* means to use the768 system default, which is usually line buffered for tty devices and fully769 buffered for other files. If omitted, the system default is used. [#]_879 buffer of (approximately) that size (in bytes). A negative *buffering* means 880 to use the system default, which is usually line buffered for tty devices and 881 fully buffered for other files. If omitted, the system default is used. [#]_ 770 882 771 883 Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (note that … … 774 886 systems that don't have this distinction, adding the ``'b'`` has no effect. 775 887 776 In addition to the standard :cfunc:`fopen` values *mode* may be ``'U'`` or 777 ``'rU'``. Python is usually built with universal newline support; supplying 778 ``'U'`` opens the file as a text file, but lines may be terminated by any of the 779 following: the Unix end-of-line convention ``'\n'``, the Macintosh convention 780 ``'\r'``, or the Windows convention ``'\r\n'``. All of these external 781 representations are seen as ``'\n'`` by the Python program. If Python is built 782 without universal newline support a *mode* with ``'U'`` is the same as normal 783 text mode. Note that file objects so opened also have an attribute called 784 :attr:`newlines` which has a value of ``None`` (if no newlines have yet been 785 seen), ``'\n'``, ``'\r'``, ``'\r\n'``, or a tuple containing all the newline 786 types seen. 888 .. index:: 889 single: universal newlines; open() built-in function 890 891 In addition to the standard :c:func:`fopen` values *mode* may be ``'U'`` or 892 ``'rU'``. Python is usually built with :term:`universal newlines` support; 893 supplying ``'U'`` opens the file as a text file, but lines may be terminated 894 by any of the following: the Unix end-of-line convention ``'\n'``, the 895 Macintosh convention ``'\r'``, or the Windows convention ``'\r\n'``. All of 896 these external representations are seen as ``'\n'`` by the Python program. 897 If Python is built without universal newlines support a *mode* with ``'U'`` 898 is the same as normal text mode. Note that file objects so opened also have 899 an attribute called :attr:`newlines` which has a value of ``None`` (if no 900 newlines have yet been seen), ``'\n'``, ``'\r'``, ``'\r\n'``, or a tuple 901 containing all the newline types seen. 787 902 788 903 Python enforces that the mode, after stripping ``'U'``, begins with ``'r'``, … … 830 945 831 946 832 .. function:: print( [object, ...][, sep=' '][, end='\\n'][, file=sys.stdout])833 834 Print *object *\(s)to the stream *file*, separated by *sep* and followed by947 .. function:: print(*objects, sep=' ', end='\\n', file=sys.stdout) 948 949 Print *objects* to the stream *file*, separated by *sep* and followed by 835 950 *end*. *sep*, *end* and *file*, if present, must be given as keyword 836 951 arguments. … … 839 954 written to the stream, separated by *sep* and followed by *end*. Both *sep* 840 955 and *end* must be strings; they can also be ``None``, which means to use the 841 default values. If no *object * isgiven, :func:`print` will just write956 default values. If no *objects* are given, :func:`print` will just write 842 957 *end*. 843 958 844 959 The *file* argument must be an object with a ``write(string)`` method; if it 845 is not present or ``None``, :data:`sys.stdout` will be used. 960 is not present or ``None``, :data:`sys.stdout` will be used. Output buffering 961 is determined by *file*. Use ``file.flush()`` to ensure, for instance, 962 immediate appearance on a screen. 846 963 847 964 .. note:: … … 864 981 *fget* is a function for getting an attribute value, likewise *fset* is a 865 982 function for setting, and *fdel* a function for del'ing, an attribute. Typical 866 use is to define a managed attribute x::983 use is to define a managed attribute ``x``:: 867 984 868 985 class C(object): … … 878 995 x = property(getx, setx, delx, "I'm the 'x' property.") 879 996 997 If then *c* is an instance of *C*, ``c.x`` will invoke the getter, 998 ``c.x = value`` will invoke the setter and ``del c.x`` the deleter. 999 880 1000 If given, *doc* will be the docstring of the property attribute. Otherwise, the 881 1001 property will copy *fget*'s docstring (if it exists). This makes it possible to … … 894 1014 with the same name. 895 1015 896 A property object has :attr:` getter`, :attr:`setter`, and :attr:`deleter`897 methods usable as decorators that create a copy of the property with the898 co rresponding accessor function set to the decorated function. This is899 best explained with an example::1016 A property object has :attr:`~property.getter`, :attr:`~property.setter`, 1017 and :attr:`~property.deleter` methods usable as decorators that create a 1018 copy of the property with the corresponding accessor function set to the 1019 decorated function. This is best explained with an example:: 900 1020 901 1021 class C(object): … … 932 1052 933 1053 934 .. function:: range([start,] stop[, step]) 1054 .. function:: range(stop) 1055 range(start, stop[, step]) 935 1056 936 1057 This is a versatile function to create lists containing arithmetic progressions. … … 986 1107 a default when the iterable is empty. If *initializer* is not given and 987 1108 *iterable* contains only one item, the first item is returned. 988 1109 Roughly equivalent to:: 1110 1111 def reduce(function, iterable, initializer=None): 1112 it = iter(iterable) 1113 if initializer is None: 1114 try: 1115 initializer = next(it) 1116 except StopIteration: 1117 raise TypeError('reduce() of empty sequence with no initial value') 1118 accum_value = initializer 1119 for x in it: 1120 accum_value = function(accum_value, x) 1121 return accum_value 989 1122 990 1123 .. function:: reload(module) … … 1050 1183 1051 1184 1185 .. _func-repr: 1052 1186 .. function:: repr(object) 1053 1187 … … 1076 1210 1077 1211 1078 .. function:: round(x[, n]) 1079 1080 Return the floating point value *x* rounded to *n* digits after the decimal 1081 point. If *n* is omitted, it defaults to zero. The result is a floating point 1082 number. Values are rounded to the closest multiple of 10 to the power minus 1083 *n*; if two multiples are equally close, rounding is done away from 0 (so. for 1084 example, ``round(0.5)`` is ``1.0`` and ``round(-0.5)`` is ``-1.0``). 1085 1086 1212 .. function:: round(number[, ndigits]) 1213 1214 Return the floating point value *number* rounded to *ndigits* digits after 1215 the decimal point. If *ndigits* is omitted, it defaults to zero. The result 1216 is a floating point number. Values are rounded to the closest multiple of 1217 10 to the power minus *ndigits*; if two multiples are equally close, 1218 rounding is done away from 0 (so. for example, ``round(0.5)`` is ``1.0`` and 1219 ``round(-0.5)`` is ``-1.0``). 1220 1221 1222 .. note:: 1223 1224 The behavior of :func:`round` for floats can be surprising: for example, 1225 ``round(2.675, 2)`` gives ``2.67`` instead of the expected ``2.68``. 1226 This is not a bug: it's a result of the fact that most decimal fractions 1227 can't be represented exactly as a float. See :ref:`tut-fp-issues` for 1228 more information. 1229 1230 1231 .. _func-set: 1087 1232 .. function:: set([iterable]) 1088 1233 :noindex: 1089 1234 1090 Return a new set, optionally with elements are taken from *iterable*. 1091 The set type is described in :ref:`types-set`. 1092 1093 For other containers see the built in :class:`dict`, :class:`list`, and 1094 :class:`tuple` classes, and the :mod:`collections` module. 1235 Return a new :class:`set` object, optionally with elements taken from 1236 *iterable*. ``set`` is a built-in class. See :class:`set` and 1237 :ref:`types-set` for documentation about this class. 1238 1239 For other containers see the built-in :class:`frozenset`, :class:`list`, 1240 :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections` 1241 module. 1095 1242 1096 1243 .. versionadded:: 2.4 … … 1106 1253 1107 1254 1108 .. function:: slice([start,] stop[, step]) 1255 .. function:: slice(stop) 1256 slice(start, stop[, step]) 1109 1257 1110 1258 .. index:: single: Numerical Python … … 1112 1260 Return a :term:`slice` object representing the set of indices specified by 1113 1261 ``range(start, stop, step)``. The *start* and *step* arguments default to 1114 ``None``. Slice objects have read-only data attributes :attr:` start`,1115 :attr:` stop` and :attr:`step` which merely return the argument values (or their1116 default). They have no other explicit functionality; however they are used by1117 Numerical Python and other third party extensions. Slice objects are also1118 generated when extended indexing syntax is used. For example:1119 ``a[start:stop:step]`` or ``a[start:stop, i]``. See :func:`itertools.islice`1120 for an alternate version that returns an iterator.1262 ``None``. Slice objects have read-only data attributes :attr:`~slice.start`, 1263 :attr:`~slice.stop` and :attr:`~slice.step` which merely return the argument 1264 values (or their default). They have no other explicit functionality; 1265 however they are used by Numerical Python and other third party extensions. 1266 Slice objects are also generated when extended indexing syntax is used. For 1267 example: ``a[start:stop:step]`` or ``a[start:stop, i]``. See 1268 :func:`itertools.islice` for an alternate version that returns an iterator. 1121 1269 1122 1270 … … 1136 1284 1137 1285 *key* specifies a function of one argument that is used to extract a comparison 1138 key from each list element: ``key=str.lower``. The default value is ``None``. 1286 key from each list element: ``key=str.lower``. The default value is ``None`` 1287 (compare the elements directly). 1139 1288 1140 1289 *reverse* is a boolean value. If set to ``True``, then the list elements are … … 1144 1293 than specifying an equivalent *cmp* function. This is because *cmp* is 1145 1294 called multiple times for each list element while *key* and *reverse* touch 1146 each element only once. To convert an old-style *cmp* function to a *key* 1147 function, see the `CmpToKey recipe in the ASPN cookbook 1148 <http://code.activestate.com/recipes/576653/>`_\. 1295 each element only once. Use :func:`functools.cmp_to_key` to convert an 1296 old-style *cmp* function to a *key* function. 1297 1298 For sorting examples and a brief sorting tutorial, see `Sorting HowTo 1299 <http://wiki.python.org/moin/HowTo/Sorting/>`_\. 1149 1300 1150 1301 .. versionadded:: 2.4 … … 1158 1309 method, use this idiom:: 1159 1310 1160 class C :1311 class C(object): 1161 1312 @staticmethod 1162 def f(arg1, arg2, ...): ... 1313 def f(arg1, arg2, ...): 1314 ... 1163 1315 1164 1316 The ``@staticmethod`` form is a function :term:`decorator` -- see the … … 1168 1320 as ``C().f()``). The instance is ignored except for its class. 1169 1321 1170 Static methods in Python are similar to those found in Java or C++. For a more 1171 advanced concept, see :func:`classmethod` in this section. 1322 Static methods in Python are similar to those found in Java or C++. Also see 1323 :func:`classmethod` for a variant that is useful for creating alternate 1324 class constructors. 1172 1325 1173 1326 For more information on static methods, consult the documentation on the … … 1180 1333 1181 1334 1182 .. function:: str( [object])1335 .. function:: str(object='') 1183 1336 1184 1337 Return a string containing a nicely printable representation of an object. For … … 1200 1353 Sums *start* and the items of an *iterable* from left to right and returns the 1201 1354 total. *start* defaults to ``0``. The *iterable*'s items are normally numbers, 1202 and are not allowed to be strings. The fast, correct way to concatenate a 1203 sequence of strings is by calling ``''.join(sequence)``. Note that 1204 ``sum(range(n), m)`` is equivalent to ``reduce(operator.add, range(n), m)`` 1205 To add floating point values with extended precision, see :func:`math.fsum`\. 1355 and the start value is not allowed to be a string. 1356 1357 For some use cases, there are good alternatives to :func:`sum`. 1358 The preferred, fast way to concatenate a sequence of strings is by calling 1359 ``''.join(sequence)``. To add floating point values with extended precision, 1360 see :func:`math.fsum`\. To concatenate a series of iterables, consider using 1361 :func:`itertools.chain`. 1206 1362 1207 1363 .. versionadded:: 2.3 … … 1215 1371 :func:`getattr` except that the *type* itself is skipped. 1216 1372 1217 The :attr:`__mro__` attribute of the *type* lists the method resolution 1218 search order used by both :func:`getattr` and :func:`super`. The attribute 1219 is dynamic and can change whenever the inheritance hierarchy is updated. 1373 The :attr:`~class.__mro__` attribute of the *type* lists the method 1374 resolution search order used by both :func:`getattr` and :func:`super`. The 1375 attribute is dynamic and can change whenever the inheritance hierarchy is 1376 updated. 1220 1377 1221 1378 If the second argument is omitted, the super object returned is unbound. If … … 1259 1416 references. 1260 1417 1418 For practical suggestions on how to design cooperative classes using 1419 :func:`super`, see `guide to using super() 1420 <http://rhettinger.wordpress.com/2011/05/26/super-considered-super/>`_. 1421 1261 1422 .. versionadded:: 2.2 1262 1423 … … 1277 1438 1278 1439 .. function:: type(object) 1440 type(name, bases, dict) 1279 1441 1280 1442 .. index:: object: type 1281 1443 1282 Return the type of an *object*. The return value is a type object. The 1283 :func:`isinstance` built-in function is recommended for testing the type of an 1284 object. 1285 1286 With three arguments, :func:`type` functions as a constructor as detailed below. 1287 1288 1289 .. function:: type(name, bases, dict) 1290 :noindex: 1291 1292 Return a new type object. This is essentially a dynamic form of the 1293 :keyword:`class` statement. The *name* string is the class name and becomes the 1294 :attr:`__name__` attribute; the *bases* tuple itemizes the base classes and 1295 becomes the :attr:`__bases__` attribute; and the *dict* dictionary is the 1296 namespace containing definitions for class body and becomes the :attr:`__dict__` 1297 attribute. For example, the following two statements create identical 1298 :class:`type` objects: 1444 With one argument, return the type of an *object*. The return value is a 1445 type object. The :func:`isinstance` built-in function is recommended for 1446 testing the type of an object. 1447 1448 With three arguments, return a new type object. This is essentially a 1449 dynamic form of the :keyword:`class` statement. The *name* string is the 1450 class name and becomes the :attr:`~class.__name__` attribute; the *bases* tuple 1451 itemizes the base classes and becomes the :attr:`~class.__bases__` attribute; 1452 and the *dict* dictionary is the namespace containing definitions for class 1453 body and becomes the :attr:`~object.__dict__` attribute. For example, the 1454 following two statements create identical :class:`type` objects: 1299 1455 1300 1456 >>> class X(object): … … 1318 1474 1319 1475 1320 .. function:: unicode([object[, encoding [, errors]]]) 1476 .. function:: unicode(object='') 1477 unicode(object[, encoding [, errors]]) 1321 1478 1322 1479 Return the Unicode string version of *object* using one of the following modes: … … 1358 1515 .. function:: vars([object]) 1359 1516 1360 Without an argument, act like :func:`locals`. 1361 1362 With a module, class or class instance object as argument (or anything else that 1363 has a :attr:`__dict__` attribute), return that attribute. 1364 1365 .. note:: 1366 1367 The returned dictionary should not be modified: 1368 the effects on the corresponding symbol table are undefined. [#]_ 1369 1370 1371 .. function:: xrange([start,] stop[, step]) 1372 1373 This function is very similar to :func:`range`, but returns an "xrange object" 1517 Return the :attr:`~object.__dict__` attribute for a module, class, instance, 1518 or any other object with a :attr:`__dict__` attribute. 1519 1520 Objects such as modules and instances have an updateable :attr:`__dict__` 1521 attribute; however, other objects may have write restrictions on their 1522 :attr:`__dict__` attributes (for example, new-style classes use a 1523 dictproxy to prevent direct dictionary updates). 1524 1525 Without an argument, :func:`vars` acts like :func:`locals`. Note, the 1526 locals dictionary is only useful for reads since updates to the locals 1527 dictionary are ignored. 1528 1529 1530 .. function:: xrange(stop) 1531 xrange(start, stop[, step]) 1532 1533 This function is very similar to :func:`range`, but returns an :ref:`xrange 1534 object <typesseq-xrange>` 1374 1535 instead of a list. This is an opaque sequence type which yields the same values 1375 1536 as the corresponding list, without actually storing them all simultaneously. … … 1378 1539 very large range is used on a memory-starved machine or when all of the range's 1379 1540 elements are never used (such as when the loop is usually terminated with 1380 :keyword:`break`). 1541 :keyword:`break`). For more information on xrange objects, see 1542 :ref:`typesseq-xrange` and :ref:`typesseq`. 1381 1543 1382 1544 .. impl-detail:: … … 1388 1550 larger range is needed, an alternate version can be crafted using the 1389 1551 :mod:`itertools` module: ``islice(count(start, step), 1390 (stop-start+step-1 )//step)``.1552 (stop-start+step-1+2*(step<0))//step)``. 1391 1553 1392 1554 … … 1433 1595 1434 1596 This is an advanced function that is not needed in everyday Python 1435 programming .1597 programming, unlike :func:`importlib.import_module`. 1436 1598 1437 1599 This function is invoked by the :keyword:`import` statement. It can be 1438 replaced (by importing the :mod:` builtins` module and assigning to1439 `` builtins.__import__``) in order to change semantics of the1600 replaced (by importing the :mod:`__builtin__` module and assigning to 1601 ``__builtin__.__import__``) in order to change semantics of the 1440 1602 :keyword:`import` statement, but nowadays it is usually simpler to use import 1441 1603 hooks (see :pep:`302`). Direct use of :func:`__import__` is rare, except in … … 1484 1646 1485 1647 If you simply want to import a module (potentially within a package) by name, 1486 you can call :func:`__import__` and then look it up in :data:`sys.modules`:: 1487 1488 >>> import sys 1489 >>> name = 'foo.bar.baz' 1490 >>> __import__(name) 1491 <module 'foo' from ...> 1492 >>> baz = sys.modules[name] 1493 >>> baz 1494 <module 'foo.bar.baz' from ...> 1648 use :func:`importlib.import_module`. 1649 1495 1650 1496 1651 .. versionchanged:: 2.5 … … 1529 1684 1530 1685 .. deprecated:: 2.3 1531 Use the extended call syntax with ``*args`` and ``**keywords`` instead. 1686 Use ``function(*args, **keywords)`` instead of 1687 ``apply(function, args, keywords)`` (see :ref:`tut-unpacking-arguments`). 1532 1688 1533 1689 … … 1569 1725 1570 1726 .. [#] Specifying a buffer size currently has no effect on systems that don't have 1571 :c func:`setvbuf`. The interface to specify the buffer size is not done using a1572 method that calls :c func:`setvbuf`, because that may dump core when called after1727 :c:func:`setvbuf`. The interface to specify the buffer size is not done using a 1728 method that calls :c:func:`setvbuf`, because that may dump core when called after 1573 1729 any I/O has been performed, and there's no reliable way to determine whether 1574 1730 this is the case.
Note:
See TracChangeset
for help on using the changeset viewer.