python built-in function help documentation

Translator: butalnd translation in 2010.2.9 - 2010.2.10, personal blog:
Note that this module's function on unix are skipped most of the translation primarily for WINDOWS, quick translation, many of them inadequate, please bear with me.

There are many built-in Python interpreter function. The following list is in alphabetical order

__import__ (name [, globals [, locals [, fromlist [, level ]]]])
Import statement is called the function. It's exists primarily yes Weile you can use another one with a compatible interface to the function Lai Gai Bian import statement of the semantics. Why and how to do the examples of standard library modules ihooks and rexec. Ye can view the imp, It defines a useful Caozuo, you You can create your own __import__ () function.
For example, the statement "import spam" results correspond to the following call: __import__ ('spam', globals (), locals (), [], -1); statement "from spam.ham import eggs" results correspond to call "__import__ (' spam.ham ', globals (), locals (), [' eggs'], -1) ". Note that even though locals () and ['eggs'] as a parameter, __import__ () function does not set the local variable eggs; import statement in the code behind to complete this function. (practical work on implementation of the standards did not use local parameters, just use the import statement to declare the package globals decision context.)

When the name variable is package.module form, the normal stress, will return to the top-level package (the first point of the left part), not the module named name. However, when specifying a non-empty formlist parameter named name returns module. This is for compatibility with different types of import statements for the generated bytecode; when using the "import spam.ham.eggs", the top-level package spam must import the space, but when using "from spam.ham import eggs ", you must use spam.ham sub-package to find the eggs variable. As a working range of this behavior, use getattr () extracts the required components. For example, you can define the following:

def my_import (name):
mod = __import__ (name)
components = name.split ('.')
for comp in components [1:]:
mod = getattr (mod, comp)
return mod

level specifies whether to use relative or absolute import. The default is -1 will use to try to use relative or absolute import. 0 to use only absolute imports. positive number means that the relative level folder, find the module level parent folder called __import__.

abs (x)
Returns the absolute value of a number. Parameter may be a general or long integer or a floating point number. If the argument is a complex number, returns its product.

all (iterable)
If all elements are true iteration returns true.
def all (iterable):
for element in iterable:
if not element:
return False
return True

Version 2.5 added.

any (iterable)
If the iteration is true there is an element returns true.
def any (iterable):
for element in iterable:
if element:
return True
return False

Version 2.5 added.

basestring ()
This abstract type is the parent of str and unicode. It can not be called or initialized, but it can be used to test whether an object is an instance of str or unicode. isinstance (obj, basestring) is equivalent to isinstance (obj, (str, unicode))
Version 2.3 added.

bool ([x])
Convert a value Boolean, using the standard truth testing procedure. If x is false or omitted, will return False; otherwise returns True.bool is also a class, it is a subclass of int, bool type can not be further subclass. It is only two instances of False and True.

callable (object)
If the object parameters can be called on to return True, otherwise it returns False. If it returns True, it may still call fails, but if returned to False, will never be called successful. Note class is callable (calling a class return an instance); instance of the class if you have a __call__ () method is callable.

chr (i)
Returns a code is an integer i a ascii string of characters. For example, chr (97) returns string 'a'. This is ord () is just the opposite. This parameter in [0 .. 255] range, all included. If you exceed this range, it throws ValueError

classmethod (function)
A class method to return function. A class method
Return a class method for function. A class method receives its first class as a potential argument, as an instance method receives an instance. Declare a class method, as follows:

class C:
@ Classmethod
def f (cls, arg1, arg2, ...): ...

@ Classmethod form is a function decorator. In Chapter VII of the function reference manual description of the function definition looking for more details.
It is in a class (such as Cf) on the call, you can call in an instance. This example will ignore its class. If a derived class to call a class method, which inherits the first class object as a potential parameter.

Class method is different from C + + or Java static methods. If you want to do, use staticmethod ().

cmp (x, y)

According to compare two objects x and y refer the results, return an integer. If x <y, The return value is negative, if x==y, Returns 0 if x> y, returns a positive number.

compile (string, filename, kind [, flags [, dont_inherit]])

Compile a code object string. Object code execution through exec statement or by calling eval () calculation. This filename parameter specifies the source file from which to read. If you do not read from the file, you must pass a number of identifiable value (typically '<string>'). kind parameter specifies which code is compiled; case contains a series of statements can be composed of sub-character string 'exec', if the composition is an expression, the 'eval', if the statement by an interactive form on the 'singlw' (in the latter case, expression statements calculated result is not None will printed).
When compiling a multi-line statement, the application of two warnings: the need to '\ n' as end of line, while the input must be at least a '\ n' as end. In the case of '\ r \ n' as end of line, use the string of repalce () method to change it to '\ n'.

Can first control the parameters of flags and dont_inherit future impact statement compiled string. More details, please refer to the English documentation.

complex ([real [, imag]])

Create a complex real + imag * j or a string or number into a complex. If the first parameter is a string, it will serve as the plural interpretation, the function is called while ignoring the second parameter. The second parameter can not be a string. Each parameter type may be a number include the plural. If the imag omitted, it defaults to 0, function as a digital conversion function like int (), long () and float (). If the parameters are omitted, the Back to 0j.

delattr (object, name)
And setattr () relative parameter is an object and a string.string must be the object of a property. Function delete object attributes, called string. For example, delattr (x, 'foobar') is equivalent to del x.foobar

dict ([arg])
An optional location parameter or a set of keywords parameter to initialize a dictionary. If no arguments, returns an empty dictionary. If the location parameter arg is a mapping object, return a dictionary mapping the same keys with the corresponding map object the same value. It should be a sequence of positional parameters, to support iteration of the container, or an iterator object. Parameters of each element must be one of them, and each contains two objects. The first dictionary as a new key, while the second as the key value. If the given key is not only appear once, this new dictionary will contain the last value.
If given the keyword parameters, keywords and associated values are as dictionary entries to the dictionary. If a ke both as a location parameter and as a keyword parameter, keyword value associated with retention in the dictionary. For example, the following are equivalent for all returns ("one": 2, "two": 3):

dict (('one': 2, 'two': 3))
dict (('one': 2, 'two': 3). items ())
dict (('one': 2, 'two': 3). iteritems ())
dict (zip (('one', 'two'), (2, 3)))
dict ([['two', 3], ['one', 2]])
dict (one = 2, two = 3)
dict ([([' one ',' two '] [i-2], i) for i in (2, 3)])
Version 2.2 added.

dir ([object])
If no parameters, returns the current local symbol table, a list of names. If there is an argument to try to return a valid property of this parameter object. From the object __dict__ (if defined) property, class or type objects to gather information. This list is not necessarily complete. If the object is a module object, list contains a list of the module properties. If the object is a type or class object, the list will contain the attribute name, while the recursive property of their base. Otherwise, the list will contain the name of the object attributes, class attributes name, recursive, if the properties of the base class name. The results list alphabetically. For example:

>>> Import struct
>>> Dir ()
['__builtins__', '__doc__', '__name__', 'Struct']
>>> Dir (struct)
['__doc__', '__name__', 'Calcsize', 'error', 'pack', 'unpack']

Note: Because the dir () mainly in the interactive prompt, easy to use, it tries to provide a meaningful name, rather than to try to provide a strict definition of the same name or, in relrase behavior in its details may change.

divmod (a, b)

With two figures (not plural) as a parameter, get the business back to long division and the remainder consisting of a pair of numbers. Use a mixture of action types, mixed types, will apply the application of binary arithmetic operations. For general and long integers, the result with (a / / b, a% b) the same. For floating-point results and (q, a% b) the same, q is usually math.floor (a / b), but if it is smaller than 1, it is 1. In any case q * b + a% b and a very close to, if a% b non-0, with b have the same sign, while 0 <= abs (a% b) <abs (b).

enumerate (iterable)

Back to enumerate objects. Iterable must be a sequence, one iteration, or other object that supports iteration. Enumerate () returns the iterator's next () method returns a tuple containing a certain number (starting from 0) and from the iterative to obtain the corresponding value. enumerate () to obtain an index series is useful: (0, seq [0]), (1, seq [1]), (2, seq [2]), .... new in version 2.3.

eval (expression [, globals [, locals]])

This parameter is a string and optional globals and locals. If you provide globals, globals must be a dictionary. If you provide locals, locals can be any mapping object. Version 2.4 changes: I used to be asked to locals is a dictionary.

expression parameter is a Python expression to be analyzed and evaluated (technically speaking, a condition list) using the globals and locals dictionaries as global and the local name space. If you provide a globals dictionary but not '__builtins__', the expression was analyzed in the current globals are copied into globals in the former. This means that expressions can have full access to standard __builtin__ module and restricted environments. If the locals dictionary is omitted it defaults to globals dictionary. If both dictionaries are omitted, the expression in the execution environment calls eval. Return value is calculated expression result. Syntax error reported as exceptions. For example:

>>> X = 1
>>> Print eval ('x +1')

This function can also be used to execute arbitrary code objects (such as compile () created). In this case, pass a code object, not a string. The code object must have been compiled passing 'eval' as this parameter.

Tip: EXEC statement supports dynamic execution statement. execfile () function to support the implementation of statements from a file. globals () and locals () function returns the current global and the respective local dictionary, which uses eval () or execfile () helpful.

execfile (filename [, globals [, locals]])

This feature is similar to the EXEC statement, but the analysis of a document, not a string. This is the difference between the import statement is that it does not use the module administration - it reads the file unconditionally and does not create a new module.
The argument is a file name and two optional dictionaries. The file is a sequence of Python statements (similar to a module) using the globals and locals as the global and local name space to analysis and calculation. If you provide locals, locals can be any mapping object. Version 2.4 changes: I used to be asked to locals is a dictionary. If the locals dictionary is omitted it defaults to the global dictionary. If both dictionaries are omitted, the expression execfile () is called the implementation environment. Return value is None.

Warning: The default locals for the following locals (): Do not attempt to modify the default local dictionary. If you need to see the function execfile () return code of locals, pass an explicit locals dictionary. execfile () can not be used to modify the functions dependent on locals.

file (filename [, mode [, bufsize]])

File type constructor, 3.9 and further described in the object `file '. Argument to the constructor with the following built-in open () function is the same.
When you open a file, it is best to use the open (), instead of directly calling this constructor. File is more suitable for test type (for example, isinstance (f, file)).

Version 2.2 added.

filter (function, iterable)

function returns true, the elements from the iterable construct a list. Iteration can be a sequence container that supports iteration, or an iterator, if Iterable is a string or a tuple, the result also of this type, otherwise it is always a list. If function is None, assume that it is identity function, that is, iteration is false in all its elements are removed.
Please note, filter (function, iterable), None if the function is not equivalent to [item for item in iterable if function (item)], if function is None is equivalent to [item for item in iterable if item].

float ([x])

A string or a digital converter or a floating point number. If the parameter is a string, it must contain a possible sign of the decimal or floating-point belt, may be embedded spaces. Otherwise, the parameter can be a normal or long integer or floating-point, return a floating point number with the same value (within the Python floating point precision). If no arguments, returns 0.0.
Note: When passing a string may return NaN and Infinity, which depends on the underlying C library.

frozenset ([iterable])

Returns a frozenset object, the element from Iterable. Frozensets group did not update the method, but hash and other groups can be members or as dictionary keys. A frozenset elements must be immutable. Within the sets should also be frozenset object. If iteration is not specified, returns a new empty set, frozenset ([]). New in version 2.4

getattr (object, name [, default])

Back to object attribute called name. Name must be a string. If the string is the object of one attribute name, the result is the value of the property. For example, getattr (x, 'foobar') is equivalent to x.foobar. If the specified attribute does not exist, then return to the default provided, or throw AttributeError.

globals ()

Return on behalf of the current global symbol table dictionary dictionary. This is always the current module dictionary (within a function or method, it is defined in the module, instead of being called a module).
hasattr (object, name)

This parameter is an object and a string. If the string is one of the object properties, the result is True, if not return False. (This is done by calling getattr (object name) to see if an exception is thrown or not.)

hash (object)

Back to object (if any) of the hash value. Hash value is an integer. They are used to find in the dictionary, the dictionary keys, as a quick comparison key. Have the same hash value and the value equal to (even if they belong to different types, as is the case 1 and 1.0).
help ([object])

Call the built-in help system. (This function is for interactive use.) If no arguments, the interactive help system to explain the console launch. If the parameter is a string, then the string is as a module, function, class, method, keyword, or document the name and theme name to find the help pages to print out after the console. If the parameter is any other type of object, the object will have a help page. Version 2.2 added.

hex (x)

Convert an integer number (of any size) to a hexadecimal string. The result is a valid Python expression. Changed in version 2.4: Formerly only returned an unsigned literal.
Conversion of a (any size) integer as a hexadecimal string. The result is a valid Python expression. Changes in the 2.4 version: the original produced only an unsigned text.
id (object)

Back to object `` identity''. This is an integer (or long integer), which is guaranteed to be unique, and as long as the life cycle of the object. The life cycle of two non-overlapping objects may have the same ID () value. (Implementation note: This is the object of address.)

input ([prompt])

Warning: This function is unsafe because of user error input! It looked forward to a valid Python expression as input, if the input syntax is invalid, throws SyntaxError. If calculated in the course of a mistake, will throw other exceptions. (On the other hand, sometimes you need to write for the specific use of a quick script.)

If the readline module is loaded, input () will use it to provide a detailed line editing and history features.
Consider using the raw_input () function as a general input from the user.

int ([x [, radix]])

Converted to a string or number for the pure integer. If the parameter is a string, it must contain a decimal number may be signed as a Python integer, may be embedded spaces. To radix parameter gives the base as the basis for conversion (which is the default 10), can be any in the [2,36] range of integers, or zero. If the base is zero, according to the contents of the string guess the correct base. If the specified base x is not a string, cause TypeError exception. Otherwise, the parameter can be a normal or long integer or floating point. Convert floating-point truncation to integer (up to zero). If the parameter is an integer outside, will return a long object. If no arguments, returns 0

isinstance (object, classinfo)

Returns true if the object parameter is an instance of classinfo, or (directly or indirectly) sub-class. Also returns true if classinfo is a type object (new-style class) and is the type or the (direct or indirect) subclass of the object. If the object is not a class or an instance of a given type of object, the function returns false. If classinfo neither a class object nor a type object, it may be a class or type of object that contains the tuple, also may contain other recursive tuple (sequence type is not accepted). If classinfo not a class, type or tuple type, type, or this element group, will throw a TypeError exception.

issubclass (class, classinfo)

Returns true if the class is classinfo (direct or indirect) subclass. A class is considered a sub-class of their own. classinfo may be class objects per group, in which case each classinfo lane roadway in the group item will be tested. In any other case, throw a TypeError exception.

iter (o [, sentinel])

Returns an iterator object. The first parameter has different interpretations, depending on the existence of the second parameter determined. If no second argument, o must be a collection of objects to support iteration protocol (__iter__ () method), or it must support the sequence protocol (integer 0 to the beginning of the parameter __getitem__ () method). If it does not support these protocols, TypeError exception will be thrown. If the second argument, sentinel, is given, then o must be a callable object. In this case, create an iterator for each call o no reference to its next () method, if the return value is equal to sentinel, will throw StopIteration, otherwise will return other values.

len (s)

Returns the length of an object. Parameter can be a sequence (string, tuple or list) or mapping (dictionary).

list ([iterable])

Returns a list of items and can order the same iteration of the project and the same items. Iteration can be a sequence, a container to support iteration, or an iterator object. If iterable is already a list, returns a copy, similar in iterable [:]. For example, list ('abc') returns ['a', 'b', 'c'] and list ((1, 2, 3)) returns [1,2,3]. If no arguments and returns a new empty list, [].

locals ()

Update and return to a representative of the current local symbol table of the dictionary. Warning: the contents of this dictionary should not be modified, the change may not affect the interpreter used by the local variable value.

long ([x [, radix]])

Convert a string or number to a long integer. If the parameter is a string, it must contain a possible sign of any size figure, and possibly embedded spaces. radix parameter interpretation and int () the same, and only when x is a string when needed it. Otherwise, the parameter can be a normal or long integer or floating-point, to return with the same value of long integer. Convert floating point to integer truncation (up to zero). If no arguments, returns 0L.

map (function, iterable, ...)

Application function of each item in the iterable and returns a list on. If there are other iterations of the parameters, the function must take a number of parameters used items from all iterables. Shorter than the other if one iteration, will be expanded None. If function is None, the assumed identity function, if there are multiple parameters, map () returns a list containing all iterables tuple corresponding project component. Iterable argument may be a sequence or any iterable object, the result is always a list.

max (iterable [, args ...][ key])

An Iterable parameters, returns one of the largest non-empty iterable items, (such as a string, tuple or list). If multiple parameters, return the largest argument.
The optional key argument specifies a sort function with a parameter for list.sort (). key parameters, and if so, must be in keyword form (for example, "max (a, b, c, key = func)").

min (iterable [, args ...][ key])

An Iterable parameters, returns one of the smallest non-empty iterable items, (such as a string, tuple or list). If multiple parameters, return the smallest argument.
The optional key argument specifies a sort function with a parameter for list.sort (). key parameters, and if so, must be in keyword form (for example, "max (a, b, c, key = func)").

object ()

Returns a new feature of the object. All new style class object is the base class. It is a new style shared by all instances of the class.

oct (x)

Conversion of a (any size) integer to a octal string. The result is a valid Python expression.

open (filename [, mode [, bufsize]])

Open a file, return a 3.9 type described in the object file, `File Objects'. If the file is not open, IOError exception raised. When you open a file, the best call open (), rather than directly with the file structure.
The first two parameters and stdio's fopen () function, like: filename is the file name to open, mode is a string that is how the file is opened.

mode, the most common value is 'r' read, 'w' write (file if it already exists on the cut), and 'a' appended (In some Unix systems means that all writes append to the end of the file, regardless of their current seek location). If the pattern is omitted, the default is 'r' and so on. When you open a binary file, you should model value plus 'b', opened in binary mode, so as to enhance viability. (In some do not distinguish between binary and text file system append 'b',, will serve as documentation). The following are the possible mode values:

Optional bufsize argument specifies the required file buffer size: 0 means unbuffered, 1 means line buffered, any other of the positive use of its size (in some) in a buffer. Negative bufsize, use the system default, which tty devices often use line buffer, and other documents the complete buffer. If omitted, use the system default.

Mode 'r +', 'w +' and 'a +' open the file to be updated (please note, 'w +' truncates the file). Additional 'b' pattern in the distinction between binary and text files on a system to open the file in binary mode, the system does not have this distinction, adding the 'b' has no effect.

ord (c)

Given a string of length 1, returning an integer, when the parameter is a Unicode object representing the Unicode character code, or the parameter is an 8-bit string, on behalf of its byte value. For example, ord ('a') returns integer 97, ord (u '\ u2020') returns 8224. This is the 8-bit string chr () and for Unicode objects unichr () the inverse function. If the given parameters and Python Unicode is UCS2 Unicode, the character's code point must be in the range [0 .. 65535], otherwise the string length is 2, throws a TypeErro.

pow (x, y [, z])

Return x Y-th power, if given z, to return x, y th power, mode Z (more than pow (x, y)% z is more effective). These two parameters in the form of pow (x, y), is equivalent to: x ** y

property ([fget [, fset [, fdel [, doc ]]]])

Returns a new-style class (derived from the object class) properties.
fget is a get attribute value function, as fset is to set the attribute value function, fdel function to delete the attribute. Typical use is to define a managed attribute x:

class C (object):
def __init__ (self): self._x = None
def getx (self): return self._x
def setx (self, value): self._x = value
def delx (self): del self._x
x = property (getx, setx, delx, "I'm the 'x' property.")

If given, doc will be the property of the document string. Otherwise, the property will copy the document fget string (if present). This makes it possible to easily use the property () as a decorator to create read-only attributes:
class Parrot (object):
def __init__ (self):
self._voltage = 100000

@ Property
def voltage (self):
"" "Get the current voltage." ""
return self._voltage

The original voltage () method as a `getter 'read-only attribute the same name. Version 2.2 added.

range ([start,] stop [, step])

This is a generic function to create a list containing an arithmetic progression, which is often used in the loop. This parameter must be plain integers. If the step argument is omitted, the default is 1. If the start parameter is omitted, the default is 0. Complete the form is returned to a common list of integers [start, start + step, start + 2 * step, ...]. step can not be zero (otherwise cause ValueError). Such as
>>> Range (10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> Range (1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> Range (0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> Range (0, 10, 3)
[0, 3, 6, 9]
>>> Range (0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> Range (0)
>>> Range (1, 0)

raw_input ([prompt])

If the prompt argument exists, it is written to standard output, the end does not wrap. Then the function to read from the input line, to convert to a string (remove the line breaks), returned. When the EOF, throw EOFError. For example:
>>> S = raw_input ('--> ')
-> Monty Python's Flying Circus
>>> S
"Monty Python's Flying Circus"

If the ReadLine module is loaded, then raw_input () will use it to provide a detailed line editing and history features.

reduce (function, iterable [, initializer])

Use a function with two parameters from left to right calculation iterable items, reduce the iterable to get a number. For example, reduce (lambda x, y: x + y, [1, 2, 3, 4, 5]) is calculated ((((1 +2) +3) +4) +5). Left parameter x, is the running total, and the right parameters, y, is iterable in the updated value. If the optional initializer exists, the calculation can be placed in front of iterations of the items, when the iterable is empty, as the default. If no initializer, only included a return to the first.

reload (module)

Re-import previously imported module. This parameter must be a module object, so it must have been successfully imported before. If you use an external editor to edit the source files of the module, and want to try not to leave the new version of the Python interpreter, it is useful. The return value is the module object (the same value with the module parameter).
When the implementation of the reload (module) when:

Python module code re-compiled and re-run the module-level code, the definition of bindings in the module name of the new dictionary object. The second extension would not call the initialization function.
As in all other Python objects, only the reference count down to zero, the object will be recovered.

The name of the namespace in the module is updated to point to any new or changed objects.

Other old object reference (such as the name refers to the external module) will not re-bind to the new object, you must update them in each namespace, if necessary.

There are other warnings:
If a module is syntactically correct, but it failed to initialize because it is the first import statement does not bind its name locally, but in sys.modules module stores a module object (part of the initialization ). To reload the module, you must first import it again (this will bind the name to the part of the initialization module object) before you can reload () it.

When re-load a module, its dictionary (containing the module's global variables) of the reservation. Redefined the definition of the name will replace the old, so this is usually not a problem. If a module does not define a new version of the definition of the name from the old version of the old definition remains. This feature can be used to the advantage of the module, if it is to maintain global table or cache of objects ---- try statements can be tested using the table's presence and skip its initialization - if needed:

except NameError:
cache = ()

This is legitimate, despite the generally built for the Reload or dynamically loaded modules will not be too helpful, except at SYS, __main__ and __builtin__. In many cases, however, is not expansion module is designed to be initialized once more, thus any way to reload may fail.

If a module using the from ... import ... import objects from another module, called reload (), no object from which to import - a way to re-run from statement, another is to use import and qualified names (module . name).

If a module instantiates instances of classes, re-load the module defines the class does not affect the definition of an instance method - they continue to use the old class definition. The same as for the derived class.

repr (object)

Returns a string that contains printable form of an object. Sometimes is able to access an ordinary function of the operation is useful. For many types, this function makes the attempt to return a string, will produce an object and passed to the eval () the same values of the object.

reversed (seq)

Returns a reverse iterator. seq must be an agreement to support sequence objects (__len__ () method and __getitem__ () to 0 means the beginning of the integer parameter) version 2.4 in new

round (x [, n])

Return floating-point value x rounded to n places after the decimal figures. If n is omitted, the default is zero. The result is a floating point number.

set ([iterable])

Return to their elements are obtained from the iterable set. Elements must be immutable. If iterable is not specified, returns a new empty set, set ([]). new in version 2.4

setattr (object, name, value)

And getattr () corresponds to. This parameter is an object, a string and an arbitrary value. The string can be an existing property name or a new property. Function assigned to the property value, so long as the object permission. For example, setattr (x, 'foobar', 123), equivalent to x.foobar = 123.

slice ([start,] stop [, step])

Returns a slice object that represents the range (start, stop, step) the specified range. start and step arguments default to None. Slice objects have read-only data attributes start, stop and step, it just returns the parameter value (or default). No other specific functions, but their numerical Python and other third parties as extensions. When using the extended indexing syntax is also produced when the object slice. For example: "a [start: stop: step]" or "a [start: stop, i]".

sorted (iterable [, cmp [, key [, reverse]]])

Returns a new sorted list that contains the items Iterable.
Optional parameter cmp, key, reverse and list.sort () have the same meaning (see section 3.6.4).

cmp specified with two parameters (Iterable element), returns from a negative, zero or positive, the function "cmp = lambda x, y: cmp (x.lower (), y.lower ())".

key specifies a function with a parameter used to extract each element from the list a more key: "key = str.lower"

reverse is a boolean value. If set to True, then the list elements are sorted, and are to reverse every time.

In general, key and reverse conversion process is much faster than an equivalent cmp function specified. This is because the cmp is called many times for each list element, while the key and reverse touch each element only once.
New in version 2.4

staticmethod (function)

Function returns a static method. Static method does not receive an implicit first parameter. To declare a static method, as follows:

class C:
@ Staticmethod
def f (arg1, arg2, ...): ...

@ Staticmethod form is a function decorator

It is available in the class, such as Cf () calls, may also be instances, such as: C (). F (). Instance is ignored, in addition to class.

Static methods in Python is similar to Java or C + +,. For the more advanced concept, see classmethod ().

str ([object])

Returns a string that contains a description of the object can be printed. For strings, it will return the string itself. And repr (object) is different, str (object)) is not always trying to return to an eval () can accept the string, the goal is to return a printable string. If no arguments, returns an empty string,''.
sum (iterable [, start])

Seek start and be iterative from left to right and return the items and the sum of. start defaults to 0. Items in the iterable, usually a number, not a string. Fast, the correct connection string sequence is by calling''. Join (sequence). Note that sum (range (n), m) is equivalent to reduce (operator.add, range (n), m). Version 2.3 added.

super (type [, object-or-type])

Return type of the superclass. If the second parameter is omitted the super object returned is unbound. If the second parameter is an object, isinstance (obj, type) must be true. If the second parameter is a type, issubclass (type2, type) must be true. super () only for the new class.
A typical use is to call an appropriate method of super class:

class C (B):
def meth (self, arg):
super (C, self). meth (arg)

Please note, super explicit point as the process of looking for part of the binding properties, such as "super (C, self). __getitem__ (Name)". Therefore, super is undefined for the use or operation of implicit statement lookup, such as "super (C, self) [name]". Version 2.2 added.

tuple ([iterable])

Returns a tuple of items and iterable iterable is the same and have the same order. iterable may be a sequence of container supports iteration, or the iterator object. If iterable is already a tuple, a direct return. For example, tuple ('abc') returns ('a', 'b', 'c') and tuple ([1, 2, 3]) return (1, 2, 3). If no arguments and returns a new empty tuple, ().

type (object)

Return the type of object. Return value is a type of object.

type (name, bases, dict)

Returns a new type of object. This is basically a dynamic form of class declaration. The name string is the class name, a __name__ attribute; bases per group sets out in detail the base class, and become __bases__ attributes, and namespace dict dictionary is defined as a class body, as __dict__ property. For example, the following two statements create the same types of objects:
>>> Class X (object):
... A = 1
>>> X = type ('X', (object,), dict (a = 1))

Version 2.2 added.

unichr (i)

Returns a Unicode character code for the integer i, the Unicode string. For example, unichr (97) returns a string u'a '. This is a Unicode string of ord () the inverse function. Parameters of the effective range depends on how Python is configured - it can be UCS2 [0 .. 0xFFFF] or UCS4 [0 .. 0x10FFFF]. Otherwise cause ValueError. New version 2.0

unicode ([object [, encoding [, errors]]])

Back to the Unicode version of the string object, use one of the following ways:
If the given encoding and / or errors, Unicode () will decode can be a string or use 8-bit character encoding decoder buffer object. Code encoding parameter is an encoded string name; If encoding did not know, throw LookupError. Error handling is based on errors, errors in the input encoding specified character is invalid handle the situation. If the error is 'strict' (the default), trigger ValueError, while the 'ignore' to ignore the error, and 'replace' values led to the official Unicode replacement character, U + FFFD, to replace the input can not decode the characters. See codec module.

If no optional parameter, Unicode () will copy str (), but it returns Unicode strings instead of 8-bit string. Rather, if the object is a Unicode string or subclass will be returned without any additional decoding of Unicode strings.

For clients, __unicode__ () method, it will call this method without parameters to create a Unicode string. For all other objects, 8-bit string version or request representation, using the code 'strict' mode the default codec is converted to Unicode strings.

vars ([object])

If there is no argument, according to the current local symbol table to return a dictionary. If it is a module, class or class instance object as a parameter (or any other property has __dict__), based on the object's symbol table to return a dictionary. Back to the dictionary should not be be modified: the impact of the corresponding symbol table are undefined.

xrange ([start,] stop [, step])

This feature is very similar to the range (), but returns a 'xrange object' rather than a list. This is an opaque sequence type, the list contains the corresponding values are not actually the same store these values. advantage of xrange () than the range () is very small (xrange () still have to create the requested value), unless a very large range of memory, all the elements of the machine or never used (for example, to break the cycle is usually terminated by a).

Note: xrange () is to design a simple and fast. Imposed certain restrictions, in order to achieve this goal. Python in the C language to restrict all parameters to native C longs ("short" Python integers), and requested that these elements are compatible with the native C long.

zip ([iterable, ...])

This function returns a tuple list, which tuple contains the i-series or iterables each of the first i elements. Returned length parameter list is truncated length of the shortest sequence. When multiple parameters are the same length, zip () with no parameter initialization is similar to map (). A single sequence argument, it returns a list of one yuan group. With no arguments, it returns an empty list.

Translator: butalnd translation in 2010.2.9 - 2010.2.10, personal blog:
Note that this module's function on unix are skipped most of the translation primarily for WINDOWS, quick translation, many of them inadequate, please bear with me.

分类:Python 时间:2010-02-20 人气:329
blog comments powered by Disqus


  • oracle database configuration NLS_SORT alphabetical order and [transfer] 2010-11-11

    Prior to Oracle9i, Chinese is the sort of binary code in accordance with. Added in accordance with oracle9i in pinyin, radical, stroke sorting. 1, set parameter values NLS_SORT SCHINESE_RADICAL_M in accordance with the radical (first order), stroke (

  • alphabetical order and NLS_SORT oracle database configuration [turn] 2010-11-11

    Prior to Oracle9i, the Chinese are sort of in accordance with binary code. In oracle9i added in accordance with pinyin, radical, stroke sorting. 1, set parameter values ​​NLS_SORT SCHINESE_RADICAL_M by radical (first order), stroke (second order) SCH

  • Turn: oracle by alphabetical order 2011-01-21 Find some relevant information, say that is not very clear, he also studied, and eventually figured it out, we want to help. Be noted that the method requires the following version ORACLE9i and above is supporte

  • MYSQL to UTF-8 encoding in the field by alphabetical order 2010-11-14

    Using the mysql default character set is utf8, the result you want the Chinese there is a problem according to alphabetical order, discharged from the order of a mess, not what we wanted. Solution is as follows: 1, do not want to change the table def

  • Oracle 10g How to user names, in alphabetical order. Query 2010-11-20

    Oracle 9i introduces a new system comes with additional sorting functions 1, alphabetical order added in oracle9i in accordance with Pinyin, radical, stroke sorting. NLS_SORT value set SCHINESE_RADICAL_M in accordance with the radical (first order),

  • Database characters by alphabetical order 2010-12-14

    Database characters by alphabetical order 2009-06-17 12:19 SQLServer: SELECT * FROM dept ORDER BY name COLLATE Chinese_PRC_CS_AS_KS_WS Oracle: 1. / / By alphabetical order select * from dept order by nlssort (name, 'NLS_SORT = SCHINESE_STROKE_M'); 2.

  • Mysql query first alphabetical order by pinyin 2010-12-24

    Alphabetical order by A, select * from `table` where ELT (INTERVAL (CONV (HEX (left (CONVERT (field names USING gbk), 1)), 16,10), 0xB0A1, 0xB0C5, 0xB2C1, 0xB4EE, 0xB6EA, 0xB7A2, 0xB8C1, 0xB9FE, 0xBBF7, 0xBFA6, 0xC0AC, 0xC2E8, 0xC4C3, 0xC5B6, 0xC5BE,

  • MySQL character field in alphabetical order and backup 2010-09-18

    UTF-8 encoded database, if you want character field in accordance with alphabetical order: SELECT * FROM students ORDER BY CONVERT( name USING gbk ) ; Original Address: Database backup

  • Database of Chinese characters by alphabetical order 2010-12-14

    Database of Chinese characters by alphabetical order 2009-06-17 12:19 SQLServer: SELECT * FROM dept ORDER BY name COLLATE Chinese_PRC_CS_AS_KS_WS Oracle: 1 / / by alphabetical order select * from dept order by nlssort (name, 'NLS_SORT = SCHINESE_STRO

  • mysq in alphabetical order 2011-01-21

    mysq in alphabetical order SELECT * FROM table ORDER BY CONVERT (your field name USING gbk); You can re-use convert () method, the other characters on the field for secondary sorting

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 黔ICP备15002463号-1

processed in 0.308 (s). 12 q(s)