Python built-in functions 2

Source: Internet
Author: User

Import__ (name[, globals[, locals[, fromlist[, level]])
The function that is called by the import statement. It exists primarily for you to change the semantics of an import statement with another function that has a compatible interface. Why and how to do examples of standard library modules Ihooks and rexec. You can also view the IMP, which defines useful operations,
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"
The result corresponds to the call "__import__ (' Spam.ham ', globals (), locals (), [' Eggs '],-1)".

Attention is
Locals () and [' eggs '] are passed as arguments, and the __import__ () function does not set local variable eggs; The code behind the import statement ends
Into this function. (In fact, the implementation of the standard does not use local parameters, only using Globals to determine the import statement declaration
The context of the package.)

When the name variable is in the form of package.module, it is normal to return the top-level package (the part to the left of the first point) instead of the module named name. However, when a non-empty formlist parameter is specified, a module named name is returned. This is done in order to be compatible with
The byte code generated by the same kind of import statement; When using "Import Spam.ham.eggs", the top-level package spam must be in the imported space, but when using "from Spam.ham import eggs", you must use the Spam.ham child package to find the eggs variable. As an act of this kind
Working interval, use GETATTR () to extract 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 a relative or absolute import. The default is-1 will try to use a relative or absolute import. 0 Use absolute import only. A positive number means that the __import__ is called in the parent folder of the level layer relative to the Find module folder.

ABS (x)
Returns the absolute value of a number. The parameter may be a normal or long integer, or a floating-point number. If the argument is a complex number, it returns the product.

All (iterable)
Returns true if all elements of the iteration are true.
def all (iterable):
For element in iterable:
If not element:
Return False
Return True

Any (iterable)
Returns true if an element in the iteration is true.
def any (iterable):
For element in iterable:
If element:
Return True
Return False

Basestring ()
This abstract type is the parent class for STR and Unicode. It cannot 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))

BOOL ([x])
Converts a value to a Boolean, using the standard true test program. Returns False if X is false or omitted; True.bool is also a class, which is a subclass of int, and the bool class cannot be further subclasses. It only has a false and True two real
Cases.

Callable (object)
Returns True if the object parameter can be called, otherwise False is returned. If true, it is still possible for the call to fail, but if False is returned, it is never possible to invoke success. The note class is callable (call a class to return an instance); If there is an instance of the class
The _call__ () method is callable.

Chr (i)
Returns a string that is the character of an ASCII code that is an integer i. For example, CHR (97) Returns string ' a '. This is just the opposite of Ord (). This parameter is contained between [0..255]. If this range is exceeded, the ValueError classmethod (function) is thrown.
Returns a class method for a function. A class method

Return A class method for function. A class method receives a class as its first potential parameter, just 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. Find more details on the description of the function definition in the seventh chapter of the function Reference manual.

It can be called on a class (for example, C.F) or on an instance. This instance ignores its class. If an inheriting class invokes a class method, this inheriting class object is passed as the first potential parameter.
Class methods are different from the static methods of C + + or Java. If you want to do this, use Staticmethod ().

CMP (x, y)
Returns an integer based on the comparison of the results of the two objects x and Y. 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])
Compiles a string into a code object. Code objects can be executed either through the EXEC statement or by calling Eval (). This filename parameter specifies which file the code reads from. If you do not read from a file, you must pass some recognizable values (usually ' <string> '). The kind parameter specifies which code is compiled, and if it is a string of substrings that consists of a series of statements that can ' exec ', if
An expression consists of ' eval ', if it consists of an interactive statement consisting of ' SINGLW ' (in the following example, the expression statement evaluates to none of the results will be printed out).
When compiling a multiline statement, apply two warnings: ' \ n ' must be used as the line terminator, and the input must end with at least one ' \ n '.
If you end with ' \ r \ n ' as the line, use the Repalce () method of string to change it to ' \ n '.
The first parameter, flags and Dont_inherit, controls the future statement that affects string compilation.

Complex ([real[, Imag]])
Create a complex real + imag*j or convert a string or number to a complex number. If the first argument is a string, it will be interpreted as a complex number, and the function will be called, ignoring the second argument. The second parameter cannot be a string. Each parameter
Number may be a numeric type including complex numbers. If IMAG is omitted, it defaults to 0, and the function will act as a number conversion function like int (),


Long () and float (). If the arguments are omitted, the 0J is returned.
Delattr (object, name) is relative to SetAttr (), the argument is an object and a string.string must be an attribute of the object. The function removes the object named string property. For example, delattr (x, ' Foobar ') is equivalent to Del X.foobar

Dict ([ARG])
Initializes a dictionary with an optional positional parameter or a set of keyword parameters. If no arguments are given, an empty dictionary is returned. If the positional parameter arg is a mapping object, returns a dictionary map with the same value as the Map object. Then the location parameter
The number should be a sequence, a container that supports iterations, or an iterative object. Each element of a parameter must also be one of them, and each contains two objects. The first one as the key for the new dictionary, and the second as the value of the key. If a given key is not just
Appears once, the new dictionary will contain the last value.
If the keyword argument is given, the keyword and its associated value are added to the dictionary as a dictionary item. If a ke is used both as a positional parameter and as a keyword parameter, the value associated with the keyword will remain in the dictionary. For example, all of the following returns are equivalent to
{"One": 2, "one": 3}:
Dict ({' One ': 2, ' One ': 3})
Dict ({' One ': 2, ' both ': 3}.items ())
Dict ({' One ': 2, ' both ': 3}.iteritems ())
Dict (Zip (' one ', ' both '), (2, 3))
Dict ([' One ', 2]], [[' One ', ' 3]]
Dict (one=2, two=3)
Dict ([[' One ', ' II '][i-2], i) for I in (2, 3)])

Dir ([Object])
If there are no parameters, returns a list of the names in the current local symbol table. If there is a parameter that will attempt to return a valid property of this Parameter object. Collects information from the object's __dict__ (if defined) property, class, or type object. This list is not necessarily complete. If
The object is a module object, and the list contains a listing of the module properties. If the object is a type or class object, the list will contain the name of the property and recursively attribute its base. Otherwise, the list will contain the name of the object property, the name of the class property, the property of the recursive destructors class
Name. The list of results is sorted alphabetically. For example:

>>> Import struct
>>> dir ()
[' __builtins__ ', ' __doc__ ', ' __name__ ', ' struct ']
>>> dir (struct)
[' __doc__ ', ' __name__ ', ' calcsize ', ' Error ', ' pack ', ' unpack ']
Note: Because Dir () is primarily easy to use with interactive hints, it attempts to provide an interesting name instead of trying to provide a strict or defined
The same name, in Relrase, its detail behavior may change.

Divmod (A, B)
Using two numbers (not complex numbers) as parameters, returns a pair of numbers consisting of the quotient and remainder of long division. Using a mixed type of operation, the mixed types apply binary arithmetic operations to the app. For general and long integers, the result is the same as (A//b, a% b). For floating
The points result is the same as (Q, a% b), q is usually Math.floor (A/b), but if it is smaller than 1, it is 1. In any case Q * b + a% B is close to a, if a% b is 0, it has the same symbol as B and 0 < = ABS (a% B) < ABS (b).

Enumerate (iterable)
Returns the Enumerate object. Iterable must be a sequence, an iteration, or other object that supports iterations. The next () method of the iterator returned by enumerate () returns a tuple that contains a certain number (starting at 0) and the corresponding value obtained from the iteration.
Enumerate () is useful for getting an index series: (0, Seq[0]), (1, seq[1]), (2, seq[2])

Eval (expression[, globals[, locals])
The parameter is a string and optional globals and locals. If provided globals,globals must be a dictionary. If provided locals,locals can be any mapping object. 2.4 Version Modification: Previously locals was asked to be a dictionary.
The expression parameter is parsed and evaluated as a Python expression (technically, a list of conditions) using the globals and locals dictionaries as the global and local namespaces. If the Globals dictionary is provided but there is no ' __builtins__ ', the current globals
Copied to globals before the expression is parsed. This means that the expression has full access to standard __builtin__ modules and restricted environments.
If the locals dictionary is omitted, the default is the Globals dictionary. If two dictionaries are omitted, the expression executes in an environment that calls Eval.
The return value is the result of the evaluation expression. The syntax error is reported as exceptions. For example:

>>> x = 1
>>> Print eval (' x+1 ')
2
This function can also be used to execute arbitrary code objects (such as compile () created). In this case, a code object is passed in instead of a string. The code object must have been compiled to ' eval ' as such parameter.

Tip: EXEC statement support is a dynamic execution statement. The execfile () function supports executing statements from a file. The Globals () and locals () functions return the current global and local dictionaries respectively, which is useful for using eval () or execfile ().
ExecFile (filename[, globals[, locals]) This feature is similar to the EXEC statement, but parses a file instead of a string. This is different because its import statement does not use module management-it reads the file unconditionally and does not create a new module.
This parameter is a file name and two optional dictionaries. The file is used as a sequence of Python statements (similar to a module) using Globals
And locals as the global and local namespaces for analysis and calculation. If provided locals,locals can be any mapping object. Previously locals was asked to be a dictionary. If the locals dictionary is omitted, the default is the global dictionary. If two dictionaries are
is omitted, the expression execfile () is executed in the invoked environment. The return value is None.

Warning: The default locals is the following locals (): Do not attempt to modify the default local dictionary. If you need to see the effect of locals code after the function execfile () is returned, pass an explicit locals dictionary. ExecFile () cannot be used on locals that depend on modifying a function.

File (filename[, mode[, BufSize])
Constructor for file type
File object '. The parameters of the constructor are the same as the built-in open () function below.
When opening a file, it is best to use the open () instead of calling this constructor directly. The file is more suitable for the test type (for example, Isinstance (f, file)).

Filter (function, iterable)
The function returns True when a list is constructed from an element of iterable. An iteration can be a sequence, a container that supports iterations, or an iterator, and if iterable is a string or a tuple, the result also has this type, otherwise it is always a column
Table. If function is None, assume that it is an identity function, that is, the iteration is false and all its elements are deleted.

Note that the filter (function,iterable), if the function is not none equivalent to [item for item in Iterable if function (item)], if the function is none equivalent to [item for item in Iterable if item].

float ([x])
Converts a string or number or a float. If the argument is a string, it must contain a decimal or floating-point number that may be signed, possibly embedding a space. Otherwise, the argument can be a normal or long integer or floating-point number, returning a floating-point value with the same values (within Python's floating-point precision). If no parameter is given, 0.0 is returned.
Note: When passing a string, NaN and Infinity may be returned, depending on the underlying C library.

Frozenset ([iterable])
Returns an Frozenset object whose elements are from iterable. The Frozensets group has no updated methods, but can be hashed and used by other group members or as dictionary keys. An frozenset element must be immutable. The internal sets should also be the Frozenset object. If
Iteration is not specified, returns a new empty set, Frozenset ([]).

GetAttr (object, name[, default])
Returns the value of the object named Name property. The name must be a string. If the string is the property name of the object, the result is the value of the property. For example, GetAttr (x, ' Foobar ') is equivalent to X.foobar. If the specified property does not exist, it is returned by default,
otherwise throws Attributeerror.

Globals ()
Returns a dictionary representing the current global symbol table dictionary. This is always the current module dictionary (within a function or method, is the module in which it is defined, not the module being called).

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

Hash (object)
Returns the hash value of the object (if any). The hash value is an integer. They are used when a dictionary is searched, as a quick comparison dictionary keys. Have the same hash value, and the values are equal (even if they belong to different types because it is 1 and 1.0).

Help ([Object])
Call the built-in Help system. (this feature is used for interaction.) If no parameters are given, the interactive Help system starts interpreting the console. If the argument is a string, then the string is used as a Module,function,class,method,keyword or document
The theme name and help page name are searched and printed on the console. If the argument is any other type of object, a help page for that object will be produced.

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 a unsigned literal.
Converts an integer (any size) to a hexadecimal string. The result is a valid Python expression. Changes in version 2.4:
The original only produces an unsigned text.
The ID (object) returns the ' identity ' of the object. This is an integer (or long Integer), which is guaranteed to be unique, as long as the life cycle of the object. Two non-overlapping life-cycle objects may have the same ID () value. (Implementation Note: This is the address of the object.) )

Input ([prompt])
Warning: This function is unsafe because of user error input! It expects a valid Python expression as input and throws SyntaxError if the input is syntactically invalid. If there is an error in the calculation process, other exceptions will be thrown. (Another
On the one hand, sometimes this is a quick script you need to write for special use. If the ReadLine module is loaded, input () uses it to provide detailed line editing and historical features.
Consider using the Raw_input () function as a general input from the user.

Python built-in functions 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.