Python 2.5 Quick Reference |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Contents
Front matterVersion 2.5 (What's new?)Check updates at http://rgruet.free.fr/#QuickRef. Please report errors, inaccuracies and suggestions to Richard Gruet (pqr at rgruet.net).
Creative Commons License.
Useful links :
Tip: From within the Python interpreter, type Invocation Optionspython[w] [-dEhimOQStuUvVWxX?] [-c command | scriptFile | - ] [args]
Environment variables
Notable lexical entitiesKeywordsand del for is raise
Identifiers(letter | "_") (letter | digit | "_")*
String literalsTwo flavors:str (standard 8 bits locale-dependent strings, like ascii, iso 8859-1, utf-8, ...) and
unicode (16 or 32 bits/char in utf-16 mode or 32 bits/char in utf-32 mode);
one common ancestor basestring.
Boolean constants (since 2.2.1)
Numbers
Sequences
Dictionaries (Mappings)
Dictionaries (type
Keys must be of a hashable type; Values can be any type.
Operators and their evaluation order
Basic types and their operationsComparisons (defined between any types)
None
Boolean operators
Numeric typesFloats, integers, long integers, Decimals.
Operators on all numeric types
Bit operators on integers and long integers
Complex Numbers
Numeric exceptions
Operations on all sequence types (lists, tuples, strings)
Operations on mutable sequences (type
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Operation | Result | Notes |
|---|---|---|
| len(d) | The number of items in d | |
| dict() dict(**kwargs) dict(iterable) dict(d) |
Creates an empty dictionary. Creates a dictionary init with the keyword args kwargs. Creates a dictionary init with (key, value) pairs provided by iterable. Creates a dictionary which is a copy of dictionary d. |
|
| d.fromkeys(iterable, value=None) | Class method to create a dictionary with keys provided by iterator, and all values set to value. | |
| d[k] | The item of d with key k | (1) |
| d[k] = x | Set d[k] to x | |
| del d[k] | Removes d[k] from d | (1) |
| d.clear() | Removes all items from d | |
| d.copy() | A shallow copy of d | |
| d.has_key(k) k in d |
True if d has key k, else False |
|
| d.items() | A copy of d's list of (key, item) pairs | (2) |
| d.keys() | A copy of d's list of keys | (2) |
| d1.update(d2) | for k, v in d2.items(): d1[k] = vSince 2.4, update(**kwargs) and update(iterable) may also be used. |
|
| d.values() | A copy of d's list of values | (2) |
| d.get(k, defaultval) | The item of d with key k | (3) |
| d.setdefault(k[,defaultval]) | d[k] if k in d, else defaultval(also setting it) | (4) |
| d.iteritems() | Returns an iterator over (key, value) pairs. | |
| d.iterkeys() | Returns an iterator over the mapping's keys. | |
| d.itervalues() | Returns an iterator over the mapping's values. | |
| d.pop(k[, default]) | Removes key k and returns the corresponding value.
If key is not found, default is returned if given, otherwise KeyError is raised. |
|
| d.popitem() | Removes and returns an arbitrary (key, value) pair from d |
TypeError is raised if key is not acceptable.KeyError is raised if key k is not in the map. None is returned. None is returned and added to map. str & unicode)str and unicode types share a common base class
basestring.| Operation | Result | Notes |
|---|---|---|
| s.capitalize() | Returns a copy of s with its first character capitalized, and the rest of the characters lowercased. | |
| s.center(width[, fillChar=' ']) | Returns a copy of s centered in a string of length width, surrounded by the appropriate number of fillChar characters. | (1) |
| s.count(sub[, start[, end]]) | Returns the number of occurrences of substring sub in string s. | (2) |
| s.decode([encoding[, errors]]) | Returns a unicode string representing the decoded version of str s,
using the given codec (encoding). Useful when reading from a file or a I/O function that handles
only str. Inverse of encode. |
(3) |
| s.encode([encoding[, errors]]) | Returns a str representing an encoded version of s. Mostly used to encode a
unicode string to a str in order to print it or write it to a file
(since these I/O functions only accept str), e.g. u'légère'.encode('utf8').
Also used to encode a str to a str, e.g. to zip (codec 'zip')
or uuencode (codec 'uu') it. Inverse of decode. |
(3) |
| s.endswith(suffix [, start[, end]]) | Returns True if s ends with the specified suffix, otherwise return false.
Since 2.5 suffix can also be a tuple of strings to try. |
(2) |
| s.expandtabs([tabsize]) | Returns a copy of s where all tab characters are expanded using spaces. | (4) |
| s.find(sub [,start[,end]]) | Returns the lowest index in s where substring sub is found. Returns -1 if sub is not found. | (2) |
| s.index(sub[, start[, end]]) | like find(), but raises ValueError when the substring is not found. |
(2) |
| s.isalnum() | Returns True if all characters in s are alphanumeric, False otherwise. |
(5) |
| s.isalpha() | Returns True if all characters in s are alphabetic, False otherwise. |
(5) |
| s.isdigit() | Returns True if all characters in s are digit characters, False otherwise. |
(5) |
| s.islower() | Returns True if all characters in s are lowercase, False otherwise. |
(6) |
| s.isspace() | Returns True if all characters in s are whitespace characters, False otherwise. |
(5) |
| s.istitle() | Returns True if string s is a titlecased string, False otherwise. |
(7) |
| s.isupper() | Returns True if all characters in s are uppercase, False otherwise. |
(6) |
| separator.join(seq) | Returns a concatenation of the strings in the sequence seq, separated by string
separator, e.g.: ",".join(['A', 'B', 'C']) -> "A,B,C" |
|
| s.ljust/rjust/center(width[, fillChar=' ']) | Returns s left/right justified/centered in a string of length width. | (1), (8) |
| s.lower() | Returns a copy of s converted to lowercase. | |
| s.lstrip([chars] ) | Returns a copy of s with leading chars (default: blank chars) removed. | |
| s.partition(separ) | Searches for the separator separ in s, and returns a tuple (head, sep, tail)
containing the part before it, the separator itself, and the part after it. If the separator is not
found, returns (s, "", ""). |
|
| s.replace(old, new[, maxCount =-1]) | Returns a copy of s with the first maxCount (-1: unlimited) occurrences of substring old replaced by new. | (9) |
| s.rfind(sub[ , start[, end]]) | Returns the highest index in s where substring sub is found. Returns -1 if sub is not found. | (2) |
| s.rindex(sub[ , start[, end]]) | like rfind(), but raises ValueError when the substring is not found. |
(2) |
| s.rpartition(separ) | Searches for the separator separ in s, starting at the end of s, and returns a
tuple (head, sep, tail) containing the (left) part before it, the separator itself, and
the (right) part after it. If the separator is not found, returns ("", "", s). |
|
| s.rstrip([chars]) | Returns a copy of s with trailing chars(default: blank chars) removed, e.g.
aPath.rstrip('/') will remove the trailing '/'from aPath if it exists |
|
| s.split([ separator[, maxsplit]]) | Returns a list of the words in s, using separator as the delimiter string. | (10) |
| s.rsplit([ separator[, maxsplit]]) | Same as split, but splits from the end of the string. |
(10) |
| s.splitlines([ keepends]) | Returns a list of the lines in s, breaking at line boundaries. | (11) |
| s.startswith(prefix [, start[, end]]) | Returns True if s starts with the specified prefix, otherwise returns False.
Negative numbers may be used for start and end.
Since 2.5 prefix can also be a tuple of strings to try. |
(2) |
| s.strip([chars]) | Returns a copy of s with leading and trailing chars(default: blank chars) removed. | |
| s.swapcase() | Returns a copy of s with uppercase characters converted to lowercase and vice versa. | |
| s.title() | Returns a titlecased copy of s, i.e. words start with uppercase characters, all remaining cased characters are lowercase. | |
| s.translate(table [, deletechars]) | Returns a copy of s mapped through translation table table. | (12) |
| s.upper() | Returns a copy of s converted to uppercase. | |
| s.zfill(width) | Returns the numeric string left filled with zeros in a string of length width. |
sys.getdefaultencoding(), can be changed via
sys.setdefaultencoding(). Optional argument errors may be given to set
a different error handling scheme. The default for errors is 'strict', meaning
that encoding errors raise a ValueError. Other possible values are 'ignore' and
'replace'. See also module codecs.False if string s does not contain at least one character. False if string s does not contain at least one cased character. None, any whitespace string is a separator.
If maxsplit is given, at most maxsplit splits are done. formatString % args --> evaluates to a string
%[flag][width][.precision] formatCodewhere formatCode is one of c, s, i, d, u, o, x, X, e, E, f, g, G, r, % (see table below).
| Format string | Result |
|---|---|
'%3d' % 2 | ' 2' |
'%*d' % (3, 2) | ' 2' |
'%-3d' % 2 | '2 ' |
'%03d' % 2 | '002' |
'% d' % 2 | ' 2' |
'%+d' % 2 | '+2' |
'%+3d' % -2 | ' -2' |
'%- 5d' % 2 | ' 2 ' |
'%.4f' % 2 | '2.0000' |
'%.*f' % (4, 2) | '2.0000' |
'%0*.*f' % (10, 4, 2) | '00002.0000' |
'%10.4f' % 2 | ' 2.0000' |
'%010.4f' % 2 | '00002.0000' |
'%s has %03d quote types.' % ('Python', 2) == 'Python has 002 quote types.'a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python'}
(vars() function very handy to use on right-hand-side) | Code | Meaning |
|---|---|
| d | Signed integer decimal. |
| i | Signed integer decimal. |
| o | Unsigned octal. |
| u | Unsigned decimal. |
| x | Unsigned hexadecimal (lowercase). |
| X | Unsigned hexadecimal (uppercase). |
| e | Floating point exponential format (lowercase). |
| E | Floating point exponential format (uppercase). |
| f | Floating point decimal format. |
| F | Floating point decimal format. |
| g | Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise. |
| G | Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise. |
| c | Single character (accepts integer or single character string). |
| r | String (converts any python object using repr()). |
| s | String (converts any python object using str()). |
| % | No argument is converted, results in a "%" character in the result. (The complete specification is %%.) |
| Flag | Meaning |
|---|---|
| # | The value conversion will use the "alternate form". |
| 0 | The conversion will be zero padded. |
| - | The converted value is left adjusted (overrides "-"). |
| (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. | |
| + | A sign character ("+" or "-") will precede the conversion (overrides a "space" flag). |
substitute or safe_substitute methods (substitute throws KeyError if a
key is missing while safe_substitute ignores it) :
t = string.Template('Hello $name, you won $$$amount') # (note $$ to literalize $)
t.substitute({'name': 'Eric', 'amount': 100000}) # -> u'Hello Eric, you won $100000'
file). Created with built-in functions
open() [preferred] or its alias
file(). May be created
by other modules' functions as well.| Operation | Result |
|---|---|
| f.close() | Close file f. |
| f.fileno() | Get fileno (fd) for file f. |
| f.flush() | Flush file f's internal buffer. |
| f.isatty() | 1 if file f is connected to a tty-like dev, else 0. |
| f.next() | Returns the next input line of file f, or raises StopIteration when EOF is hit.
Files are their own iterators. next is implicitly called by
constructs like for line in f: print line. |
| f.read([size]) | Read at most size bytes from file f and return as a string object. If size omitted, read to EOF. |
| f.readline() | Read one entire line from file f. The returned line has a trailing \n, except possibly at EOF. Return '' on EOF. |
| f.readlines() | Read until EOF with readline() and return a list of lines read. |
| f.xreadlines() | Return a sequence-like object for reading a file line-by-line without reading the entire file into memory. From 2.2, use rather: for line in f (see below). |
| for line in f: do something... | Iterate over the lines of a file (using readline) |
| f.seek(offset[, whence=0]) | Set file f's position, like "stdio's fseek()". whence == 0 then use absolute indexing. whence == 1 then offset relative to current pos. whence == 2 then offset relative to file end. |
| f.tell() | Return file f's current position (byte offset). |
| f.truncate([size]) | Truncate f's size. If size is present, f is truncated to (at most) that size, otherwise f is truncated at current position (which remains unchanged). |
| f.write(str) | Write string to file f. |
| f.writelines(list) | Write list of strings to file f. No EOL are added. |
EOFError IOError set and frozenset (immutable set). Sets are unordered collections of unique
(non duplicate) elements. Elements must be hashable. frozensets are hashable (thus can be
elements of other sets) while sets are not. All sets are iterable.Set and ImmutableSet were
available in the module sets.This module remains in the 2.4 std library
in addition to the built-in types.| Operation | Result |
|---|---|
| set/frozenset([iterable=None]) | [using built-in types] Builds a set or frozenset
from the given iterable (default: empty), e.g. set([1,2,3]), set("hello").
|
| Set/ImmutableSet([iterable=None]) | [using the sets module] Builds a Set or ImmutableSet
from the given iterable (default: empty), e.g. Set([1,2,3]).
|
| len(s) | Cardinality of set s. |
| elt in s / not in s | True if element elt belongs / does not belong to
set s. |
| for elt in s: process elt... | Iterates on elements of set s. |
| s1.issubset(s2) | True if every element in s1 is in s2. |
| s1.issuperset(s2) | True if every element in s2 is in s1. |
| s.add(elt) | Adds element elt to set s (if it doesn't already exist). |
| s.remove(elt) | Removes element elt from set s.
KeyError if element not found. |
| s.discard(elt) | Removes element elt from set s if present. |
| s.pop() | Removes and returns an arbitrary element from set s;
raises KeyError if empty. |
| s.clear() | Removes all elements from this set (not on immutable sets!). |
| s1.intersection(s2) or s1&s2 | Returns a new Set with elements common to s1 and s2. |
| s1.union(s2) or s1|s2 | Returns a new Set with elements from both s1 and s2. |
| s1.difference(s2) or s1-s2 | Returns a new Set with elements in s1 but not in s2. |
| s1.symmetric_difference(s2) or s1^s2 | Returns a new Set with elements in either s1 or s2 but not both. |
| s.copy() | Returns a shallow copy of set s. |
| s.update(iterable) | Adds all values from iterable to set s. |
mxDateTime.
- Module objects
- Class objects
- Class instance objects
- Type objects (see module: types)
- File objects (see above)
- Slice objects
- Ellipsis object, used by extended slice notation (unique, named
Ellipsis)- Null object (unique, named
None)- XRange objects
- Callable types:
- User-defined (written in Python):
- User-defined Function objects
- User-defined Method objects
- Built-in (written in C):
- Built-in Function objects
- Built-in Method object
- Internal Types:
- Code objects (byte-compile executable Python code: bytecode)
- Frame objects (execution frames)
- Traceback objects (stack trace of an exception)
| Statement | Result |
|---|---|
| pass | Null statement |
| del name[, name]* | Unbind name(s) from object. Object will be indirectly (and automatically) deleted only if no longer referenced. |
| print[>> fileobject,] [s1 [, s2 ]* [,] | Writes to sys.stdout, or to fileobject if supplied. Puts spaces between arguments.
Puts newline at end unless statement ends with comma [if nothing is printed when using a comma,
try calling system.out.flush()]. Print is not required when running interactively,
simply typing an expression will print its value, unless the value is None. |
| exec x [in globals [, locals]] | Executes x in namespaces provided. Defaults to current namespaces. x can be a string, open file-like object
or a function object. locals can be any mapping type, not only a regular Python dict.
See also built-in function execfile. |
| callable(value,... [id=value] , [*args], [**kw]) | Call function callable with parameters. Parameters can be passed by name or be omitted if function defines
default values. E.g. if callable is defined as "def callable(p1=1, p2=2)""callable()" <=> "callable(1, 2)"*args is a tuple of positional arguments. **kw is a dictionary of keyword arguments. |
| Operator | Result |
Notes
|
|---|---|---|
| a = b | Basic assignment - assign object b to label a |
(1)(2)
|
| a += b | Roughly equivalent to a = a + b |
(3)
|
| a -= b | Roughly equivalent to a = a - b |
(3)
|
| a *= b | Roughly equivalent to a = a * b |
(3)
|
| a /= b | Roughly equivalent to a = a / b |
(3)
|
| a //= b | Roughly equivalent to a = a // b |
(3)
|
| a %= b | Roughly equivalent to a = a % b |
(3)
|
| a **= b | Roughly equivalent to a = a ** b |
(3)
|
| a &= b | Roughly equivalent to a = a & b |
(3)
|
| a |= b | Roughly equivalent to a = a | b |
(3)
|
| a ^= b | Roughly equivalent to a = a ^ b |
(3)
|
| a >>= b | Roughly equivalent to a = a >> b |
(3)
|
| a <<= b | Roughly equivalent to a = a << b |
(3)
|
first, second = l[0:2] # equivalent to: first=l[0]; second=l[1]
[f, s] = range(2) # equivalent to: f=0; s=1
c1,c2,c3 = 'abc' # equivalent to: c1='a'; c2='b'; c3='c'
(a, b), c, (d, e, f) = ['ab', 'c', 'def'] # equivalent to:
a='a'; b='b'; c='c'; d='d'; e='e'; f='f'
Tip: x,y = y,x swaps x and y.
a = b = c = 0
list1 = list2 = [1, 2, 3] # list1 and list2 points to the same list (l1 is l2)
result = (whenTrue if condition else whenFalse)
is equivalent to:
if condition:
result = whenTrue
else:
result = whenFalse
() are not mandatory but recommended.
| Statement | Result |
|---|---|
| if condition: suite [elif condition: suite]* [else: suite] |
Usual if/else if/else statement. See also Conditional Expressions. |
| while condition: suite [else: suite] |
Usual while statement. The else suite is executed after loop exits,
unless the loop is exited with break. |
| for element in sequence: suite [else: suite] |
Iterates over sequence, assigning each element to element. Use built-in
range function to iterate a number of times. The else suite
is executed at end unless loop exited with break. |
| break | Immediately exits for or while loop. |
| continue | Immediately does next iteration of for or while loop. |
| return [result] | Exits from function (or method) and returns result (use a tuple to return
more than one value). If no result given, then returns None. |
| yield expression | (Only used within the body of a generator function, outside a try of a
try..finally). "Returns" the evaluated expression. |
| Statement | Result |
|---|---|
| assert expr[, message] | expr is evaluated. if false, raises exception AssertionError with message.
Before 2.3, inhibited if __debug__ is 0. |
| try: block1 [except [exception [, value]: handler]+ [else: else-block] |
Statements in block1 are executed. If an exception occurs, look in except
clause(s) for matching exception(s). If matches or bare except, execute
handler of that clause. If no exception happens, else-block in else
clause is executed after block1. If exception has a value, it is put in variable
value. exception can also be a tuple of exceptions, e.g.
except(KeyError, NameError), e: print e. |
| try: block1 finally: final-block |
Statements in block1 are executed. If no exception, execute final-block (even if
block1 is exited with a return, break or continue
statement). If exception did occur, execute final-block and then immediately re-raise exception.
Typically used to ensure that a resource (file, lock...) allocated before the try is freed
(in the final-block) whatever the outcome of block1 execution.
See also the with statement below. |
| try: block1 [except [exception [, value]: handler1]+ [else: else-block] finally: final-block |
Unified try/except/finally. Equivalent to a try...except nested
inside a try..finally [PEP341].
See also the with statement below. |
|
with allocate-expression [as variable] with-block |
Alternative to the try...finally structure
[PEP343].allocate-expression should evaluate to an object that supports the context management protocol, representing a resource. This object may return a value that can optionally be bound to variable (variable is not assigned the result of expression). The object can then run set-up code before with-block is executed and some
clean-up code is executed after the block is done, even if the block raised an exception.Standard Python objects such as files and locks support the context management protocol: with open('/etc/passwd', 'r') as f: # file automatically closed on block exit- You can write your own context managers. - Helper functions are available in module contextlib. In 2.5 the statement must be enabled by: from __future__ import with_statement.
The statement will always be enabled in Python 2.6.
|
| raise exceptionInstance | Raises an instance of a class derived from Exception (preferred form of raise). |
| raise exceptionClass [, value [, traceback]] | Raises exception of given class exceptionClass with optional value value. Arg traceback specifies a traceback object to use when printing the exception's backtrace. |
| raise | A raise statement without arguments re-raises the last exception raised in the current function. |
class TextException(Exception): pass
try:
if bad:
raise TextException()
except Exception:
print 'Oops' # This will be printed because TextException is a subclass of Exception
str().StandardError, itself derived from Exception.BaseException. Raising strings as exceptions is now deprecated
(warning).sys.path).
Since 2.3, they may reside in a zip file [e.g. sys.path.insert(0, "aZipFile.zip")].
from __future__ import absolute_import: will probably be adopted in 2.7.import X will look up for module X in sys.path first (absolute import).import .X (with a dot) will still search for X in the current package first,
then in builtins (relative import).import ..X will search for X in the package containing the current one, etc...__init__.py (possibly empty). [package.[package...].module.symbol.| Statement | Result |
|---|---|
| import module1 [as name1] [, module2]* | Imports modules. Members of module must be referred to by qualifying with [package.]module name, e.g.:
import sys; print sys.argvmodule1 renamed as name1, if supplied. |
| from module import name1 [as othername1][, name2]* | Imports names from module module in current namespace.
from sys import argv; print argvname1 renamed as othername1, if supplied. [2.4] You can now put parentheses around the list of names in a
from module import names statement (PEP 328). |
| from module import * | Imports all names in module, except those starting with "_".
Use sparsely, beware of name clashes!
from sys import *; print argvOnly legal at the top level of a module. If module defines an __all__ attribute, only names listed in __all__
will be imported.NB: " from package import *" only imports the symbols defined in the
package's __init__.py file, not those in the package's modules ! |
| global name1 [, name2] | Names are from global scope (usually meaning from module) rather than local (usually meaning only in function). E.g. in function without global statements, assuming "x" is name that hasn't been
used in function or module so far:- Try to read from "x" -> NameError- Try to write to "x" -> creates "x" local to function If "x" not defined in fct, but is in module, then: - Try to read from "x", gets value from module - Try to write to "x", creates "x" local to fct But note "x[0]=3" starts with search for "x", will use to global "x" if no local "x". |
def funcName ([paramList]):Creates a function object and binds it to name funcName.
suiteparamList ::= [param [, param]*]
param ::= value | id=value | *id | **id
return to return (None) from the function, or return value to
return value. Use a tuple to return more than one value, e.g. return 1,2,3arg=value specify a default value
(evaluated at function def. time). They can only appear last in the param list, e.g. foo(x, y=1, s='')def foo(x, *args): ... is called foo(1, 2, 3), then args will contain
(2,3).def foo(x, **kwargs): ... is called foo(1, y=2, z=3), then kwargs will contain
{'y':2, 'z':3}. if def foo(x, *args, **kwargs): ... is called foo(1, 2, 3, y=4, z=5),
then args will contain (2, 3), and kwargs will contain {'y':4, 'z':5}def f1(x, *args, **kwargs):
f2(*args, **kwargs)
class className [(super_class1[, super_class2]*)]:Creates a class object and assigns it name className.
suite
suite may contain local "defs" of class methods and assignments to class attributes.
class MyClass (class1, class2): ...
Creates a class object inheriting from both class1 and class2. Assigns new class object to name MyClass.
class MyClass: ...
Creates a base class object (inheriting from nothing). Assigns new class object to name MyClass.
Since 2.5 the equivalent syntax class MyClass(): ... is allowed.
class MyClass (object): ...
Creates a new-style class
(inheriting from object makes a class a new-style class -available since Python 2.2-).
Assigns new class object to name MyClass.
class c (c_parent):
def __init__(self, name):
self.name = name
def print_name(self):
print "I'm", self.name
def call_parent(self):
c_parent.print_name(self)
instance = c('tom')
print instance.name
'tom'
instance.print_name()
"I'm tom"
self explicitly (see
call_parent in example above).int, float, str,
list, tuple, dict and file now (2.2) behave
like classes derived from base class object, and may be subclassed:New-style classes extendsx = int(2) # built-in cast function now a constructor for base type
y = 3 # <=> int(3) (litterals are instances of new base types)
print type(x), type(y) # int, int
assert isinstance(x, int) # replaces isinstance(x, types.IntType)
assert issubclass(int, object) # base types derive from base class 'object'.
s = "hello" # <=> str("hello")
assert isinstance(s, str)
f = 2.3 # <=> float(2.3)
class MyInt(int): pass # may subclass base types
x,y = MyInt(1), MyInt("2")
print x, y, x+y # => 1,2,3
class MyList(list): pass
l = MyList("hello")
print l # ['h', 'e', 'l', 'l', 'o']
object.
Old-style classes don't.
class C:
"A description of C"
def __init__(self):
"A description of the constructor"
# etc.
c.__doc__ == "A description of C".
c.__init__.__doc__ == "A description of the constructor"
next() returning the next element or
raising StopIteration.obj via the new built-in
function iter(obj), which calls obj.__class__.__iter__(). __iter__() and next().__iter__(); dictionaries (maps) enumerate their keys; files enumerates
their lines. list or a tuple from an
iterator, e.g. list(anIterator)for elt in
collection: if elt in collection:
x,y,z=
collection yield,
while return or raise StopIteration() are used to
notify the end of values. from __future__ import generators (not required since 2.3+) generator.next() to get the next
value until StopIteration is raised.
linkGenerator = (link for link in get_all_links() if not link.followed)
for link in linkGenerator:
...process link...
send(value). yield is now an expression
returning a value, so val = (yield i) will yield i to the caller, and will reciprocally
evaluate to the value "sent" back by the caller, or None.throw(type, value=None, traceback=None) is used to raise an exception inside the generator
(appears as raised by the yield expression).close() raises a new GeneratorExit exception inside the generator to terminate
the iteration. def genID(initialValue=0):
v = initialValue
while v < initialValue + 1000:
yield "ID_%05d" % v
v += 1
return # or: raise StopIteration()
generator = genID() # Create a generator
for i in range(10): # Generates 10 values
print generator.next()
__get__(self, obj, type=None) --> value__set__(self, obj, value) __delete__(self, obj)object).
)staticmethod(f)
to make method f(x) static (unbound).f = classmethod(f) to make method
f(theClass, x) a class method.