Python built-in functions
The Python built-in (built-in) function is created as the Python interpreter runs. In Python programs, you can call these functions at any time, and you don't need to define them. The most common built-in functions are:
Print ("Hello world!")
In the Python tutorial, we have mentioned some of the following built-in functions:
Basic datatype type ()
Look back at Dir () help () Len ()
Dictionary Len ()
Input and output of text file open ()
Loop design Range () enumerate () Zip ()
Cyclic object iter ()
function Object Map () filter () reduce ()
The following are all the actual parameters, and you can try the effect directly on the command line.
Mathematical operations
ABS ( -5) # Take the absolute value, that is, 5round (2.6) # Rounding rounding, that is 3.0pow (2, 3) # equivalent to 2**3, if it is POW (2, 3, 5), equivalent to 2**3% 5CMP (2.3, 3.2) c3/># Compare the size of two numbers Divmod (9,2) # Returns the division result and remainder Max ([1,5,2,9]) # max Min ([9,2,-4,2]) # Find Minimum sum ([2,-1,9,12]) # Sum
Type conversions
Int ("5") # is converted to an integer integerfloat (2) # converted to a floating-point number Floatlong ("23") # converted to a long integer long Integerstr (2.3) # converted to a string Stringcomplex (3, 9) # returns complex Number 3 + 9iord ("a") # "a" character corresponds to the value Chr (65) # VALUE 65 corresponds to the character unichr (65) # VALUE 65 corresponds to the Unicode character bool (0) # converted to the corresponding true and False value, in Python, 0 is equivalent to False in Pytho N, the following objects are equivalent to false: [], (), {}, 0, None, 0.0, ' Bin (56) # Returns a String representing 56 of the binary Hex (56) # Returns a String that represents the hexadecimal number of 56 Oct (56) # Returns a String representing 5 6 Octal Number list ((a) # converted to table listtuple ([2,3,4]) # converted to a fixed value table Tupleslice (5,2,-1) # Build Subscript object Slicedict (a=1,b= "Hello", c=[1,2,3]) # construct Building a Dictionary Dictionary
Sequence operations
All ([True, 1, "hello!"]) # Whether all elements are equal to the true value of any (["", 0, False, [], None]) # If any one element equals True value sorted ([1,5,3]) # Returns a sequence of positive orders, that is [ 1,3,5]reversed ([1,5,3]) # Returns the sequence of the reverse order, i.e. [3,5,1]
Class, Object, property
# define Classclass Me (object):d EF test (self):p rint "hello!" def new_test ():p rint "New hello!" me = Me () hasattr (Me, "Test") # Check if the Me object has the Test property getattr (Me, "test") # returns the Test property setattr (Me, "test", New_test) # Set the test property to New_ Testdelattr (Me, "test") # Delete Test property isinstance (Me, Me) # Me object is the object generated by the Me class (a instance) Issubclass (Me, Object) # Whether the Me class is a subclass of the object class
Compile, execute
Repr (Me) # Returns the string expression of an object compile ("Print (' Hello ')", ' test.py ', ' exec ') # Compile the string into the Code object eval ("1 + 1") # to interpret the string expression. The parameter can also be compile () returned by the Code object exec ("Print (' Hello ')") # to interpret and execute the string, print (' Hello '). The parameter can also be a code object returned by the compile ()
Other
Input ("Please input:") # waits for input globals () # Returns the global namespace, such as global variable name, global function name locals () # return local namespace
Recently, I've been looking at Python's document, and I'm going to focus on the basics. Python's keyword, build-in Function, build-in Constants, build-in Types, build-in Exception these four aspects, in fact, when looking at the whole "the Python Standard Library" chapter is very good, which describes a lot of good topics. First of all, build-in function list, beginner's understanding, classification may be inaccurate, communicate together.
First, the mathematical operation class
ABS (x) |
Seek absolute value 1, the parameters can be integral type, can also be plural 2, if the parameter is a complex number, then return the modulus of the complex |
Complex ([real[, Imag]]) |
Create a complex number |
Divmod (A, B) |
Separate fetch and remainder Note: integral, floating-point types can be |
float ([x]) |
Converts a string or number to a float. If no parameter is returned 0.0 |
int ([x[, Base]]) |
Converts a character to an int type, and base represents the binary |
Long ([x[, Base]]) |
Converts a character to a long type |
Pow (x, y[, z]) |
Returns the Y power of X |
Range ([start], stop[, step]) |
Produces a sequence that starts with 0 by default |
Round (x[, N]) |
Rounded |
Sum (iterable[, start]) |
Sum the Set |
Oct (x) |
Convert a number to 8 binary |
Hex (x) |
Converts an integer x to a 16-binary string |
Chr (i) |
Returns the ASCII character corresponding to the integer i |
Bin (x) |
Converts an integer x to a binary string |
BOOL ([x]) |
Convert X to Boolean type |
Second, the collection class operation
Basestring () |
Super class for STR and Unicode cannot be called directly and can be used as isinstance judgment |
Format (value [, Format_spec]) |
Formatting the output string Formatted parameter order starting from 0, such as "I am {0},i like {1}" |
UNICHR (i) |
Returns the Unicode of the given int type |
Enumerate (sequence [, start = 0]) |
Returns an enumerable object that returns a tuple for the next () method of the object. |
ITER (o[, Sentinel]) |
Generates an iterator for an object, and the second parameter represents a delimiter |
Max (iterable[, args ...] [Key]) |
Returns the maximum value in the collection |
Min (iterable[, args ...] [Key]) |
Returns the minimum value in the collection |
Dict ([ARG]) |
Create a data dictionary |
List ([iterable]) |
To convert a collection class to another collection class |
Set () |
Set Object instantiation |
Frozenset ([iterable]) |
Produces an immutable set |
STR ([object]) |
Convert to String type |
Sorted (iterable[, cmp[, key[, reverse]]) |
Team Collection Sort |
Tuple ([iterable]) |
Generate a tuple type |
Xrange ([start], stop[, step]) |
The xrange () function is similar to range (), but xrnage () does not create a list, but instead returns a Xrange object that behaves like a list, but calculates the list value only when it is needed, which saves us memory when the list is large. |
Third, logical judgment
All (iterable) |
1, the elements in the collection are true when they are true 2, special, if the empty string returned to True |
Any (iterable) |
1, the elements in the collection have a true time for the true 2, special, if the empty string returned to False |
CMP (x, y) |
If x < Y, returns a negative number; x = = y, returns 0;x > y, returns a positive number |
Iv. Reflection
Callable (object) |
Checks whether object objects can be called 1, the class is can be called 2. Instances cannot be invoked unless the __call__ method is declared in the class |
Classmethod () |
1, annotations, to illustrate this way is a class method 2. Class methods can be called by the class or by instance 3. The class method is similar to the static method in Java 4. The self parameter is not required in a class method |
Compile (source, filename, mode[, flags[, Dont_inherit]]) |
Compiles source into code or AST object. The code object can be evaluated by EXEC statement execution or eval (). 1. Parameter source: string or AST (Abstract Syntax Trees) object. 2, Parameter filename: code file name, if not read from the file code is passed some recognizable values. 3. Parameter model: Specifies the kind of compiled code. can be specified as ' exec ', ' eval ', ' single '. 4. Parameter flag and Dont_inherit: These two parameters are not introduced temporarily |
Dir ([Object]) |
1, without parameters, returns the list of variables, methods, and definitions in the current scope; 2, with parameters, returns the properties of the parameter, the method list. 3. If the parameter contains method __dir__ (), the method will be called. When the argument is an instance. 4. If the parameter does not contain __dir__ (), the method will collect the parameter information to the maximum |
Delattr (object, name) |
Delete an object named Name property |
eval (expression [, globals [, locals]]) |
Evaluates the value of an expression |
ExecFile (filename [, globals [, locals]]) |
The usage is similar to exec (), the difference is that the execfile parameter filename is the file name, and the exec parameter is a string. |
Filter (function, iterable) |
Constructs a sequence that is equivalent to [item for item ' in Iterable if function (item)] 1, Parameter function: Return a value of TRUE or false functions, can be none 2. Parameter iterable: A sequence or an iterative object |
GetAttr (object, name [, Defalut]) |
Gets the properties of a class |
Globals () |
Returns a dictionary that describes the current global symbol table |
Hasattr (object, name) |
Determines whether the object contains an attribute named name |
Hash (object) |
Returns the hash value of object if object is a hash table type |
ID (object) |
Returns the unique identity of an object |
Isinstance (object, ClassInfo) |
Determine if object is an instance of class |
Issubclass (class, ClassInfo) |
Determine if it is a subclass |
Len (s) |
Return collection length |
Locals () |
Returns the current list of variables |
Map (function, iterable, ...) |
Iterate through each element to perform a function operation |
Memoryview (obj) |
Returns an object of a memory image type |
Next (iterator[, default]) |
Similar to Iterator.next () |
Object () |
Base class |
Property ([Fget[, fset[, fdel[, Doc]]) |
The wrapper class for property access, which can be set to access the setter and getter via C.x=value, etc. |
Reduce (function, iterable[, initializer]) |
The merge operation, which starts with the first two parameters, and then the first two results are processed with the third merge, and so on |
Reload (module) |
Reload Module |
SetAttr (object, name, value) |
Setting property values |
Repr (object) |
Changing an object to a printable format |
Slice () |
|
Staticmethod |
Declares a static method, which is an annotation |
Super (type[, Object-or-type]) |
Referencing a parent class |
Type (object) |
Returns the type of the object |
VARs ([object]) |
Returns the variable of the object, if no argument is similar to the Dict () method |
ByteArray ([Source [, encoding [, errors]]) |
Returns a byte array 1, if source is an integer, returns an initialized array of length source; 2. If source is a string, the string is converted to a sequence of bytes according to the specified encoding; 3. If source is an iterative type, the element must be an integer in [0, 255]; 4. If source is an object that is consistent with the buffer interface, this object can also be used to initialize the ByteArray. |
Zip ([iterable, ...]) |
is not understand, just see the matrix of the changing aspects |
V. IO operation
File (filename [, mode [, BufSize]]) |
A constructor for the file type that opens a file that is created if the file does not exist and mode is write or append. Adding ' B ' to the mode parameter will manipulate the file in binary form. Adding ' + ' to the mode parameter will allow simultaneous read and write operations to the file 1. Parameter filename: Name of the file. 2, Parameter mode: ' R ' (read), ' W ' (write), ' a ' (append). 3, parameter bufsize: If 0 is not buffered, if 1 is a row buffer, if it is a number greater than 1 indicates the size of the buffer. |
Input ([prompt]) |
Get user input It is recommended to use raw_input because the function will not capture the user's error input |
Open (name[, mode[, Buffering]) |
Open File What is the difference from file? Recommended use of Open |
Print |
Print function |
Raw_input ([prompt]) |
Set input, input is handled as String |
Vi. Other
Help ()--Information
__IMPORT__ ()--not very clear, see the phrase "Direct use of __import__ () is rare" after the No heart to look down
Apply (), buffer (), coerce (), intern ()---these are built-in functions that are out of date, so it does not explain
Vii. PostScript
Built-in functions, generally because the use of frequency is more frequent or meta-operation, so through the form of built-in functions provided, through the Python built-in function classification analysis can be seen: basic data operations are basically some mathematical operations (except subtraction), logical operations, set operations, basic IO operations , and then it is the reflection of the language itself, but also the operation of the string, is also more commonly used, especially the need to pay attention to the reflection operation.
Python supplemental--python built-in function list