I. Functional function
1. What is a function?
Functions are organized, reusable code segments that implement a single, or related function.
Functions can improve the modularity of applications and the reuse of code.
2. Definition of function
Syntax:
def functionname( parameters ): "function_Document string" function_suite return [expression]
Explain:
- The name of the function is the name of the statement block.
- The naming rule of function name is the same as variable name (function name must be identifier)
- Function has its own namespace, it can not access variables inside the function outside the function, and it can access variables outside the function inside. Usually it is necessary for the function to process external data with parameters to pass some data into the function.
- Function code blocks begin with def keywords, followed by function identifier names and parentheses ()
- Any incoming parameters and independent variables must be placed in the middle of parentheses. The middle of parentheses can be used to define parameters, and the parameter list of functions can be empty.
- Function content starts with a colon: and is indented
- The first line statement of a function can selectively use the document string -- the description of the storage function is applied
- The statement part of the function cannot be empty. Fill pass statements if empty
- return [expression] terminates the function, selectively returning a value to the caller. return without expression is equivalent to returning None
For example, see:
def my_max(x, y) : # Define a variable z,This variable is equal to x,y Medium to large value z = x if x > y else y # Return variable z Value return z # Define a function and declare a parameter def say_hi(name) : print("===Being implemented say_hi()function===") return name + ",Hello!"
3. Call of function
The call function is the execution function. If the created function is understood as a tool for some purpose, then calling the function is equivalent to using the tool.
The basic grammar is as follows:
Function name ([parametric value])
The function name refers to the name of the function to be called.
Parametric values refer to the values of the various parameters that are required to be passed in when a function is created.
It should be noted that how many parameters are created for a function, and how many values need to be passed in when calling, and the order must be the same as when creating a function.
Even if the function has no parameters, the parentheses after the function name cannot be omitted.
Explain:
- A function call is an expression
- If there is no return statement, the function returns the None object after execution
- If the function needs to return other objects, the return statement is needed.
For example, see:
#Call the two functions created earlier and execute the code as follows:a = 6 b = 9 # call my_max()Function, assigning the return value of the function to result variable result = my_max(a , b) # ① print("result:", result) # call say_hi()Function, the return value of the direct output function print(say_hi("Sun WuKong")) # ②
#Operation result
#result: 9
#===Being implemented say_hi()function===
#Hello, Monkey King
In the above program, two functions, my_max() and say_hi(), are called at code 1 and code 2 respectively. As can be seen from the following results, when a program calls a function, it can assign the return value of the calling function to a specified variable, or it can pass the return value of the function to another function as a parameter of another function.
In addition, the return statement in the body of a function can explicitly return a value. The return statement can return either a variable or an expression with a value. For example, the my_max() function above can also be abbreviated as follows:
def my_max(x, y) : # Returns an expression return x if x > y else y
4. Nesting of Functions
It refers to a function in which def statements are used to create other functions.
Example:
def fn_outer(): print("fn_outer Be called!") def fn_inner(): print("fn_inner Be called") fn_inner() fn_inner() print('fn_outter End of call') fn_outer()
5. Provide documentation for functions
You can use Python's built-in help() function to view help documents for other functions, and we often use help() function to view help information for specified functions, which is very important for Python developers.
We can also write a description document for a function, as long as a string is placed after the function declaration and before the function body, the string will be treated as part of the function. This document is the description document for the function.
The program can either view the description document of the function through help() function or access the description document of the function through the _doc_ attribute of the function. The following program demonstrates how to write documentation for functions:
def my_max(x, y) : ''' Gets a function with a larger number between two values. my_max(x, y) Returns the larger one between the x and y parameters ''' # Define a variable z, which is equal to the larger values in x and y z = x if x > y else y # Returns the value of variable z return z
The above program uses the grammar of multi-line strings to write a description document for my_max() function. Next, the program can either view the description document of the function through help() function or access the description document of the function through doc_ attribute.
# Use help() function to view my_max help document help(my_max) Or print(my_max.__doc__) # Operation results Help on function my_max in module __main__: my_max(x, y) Gets a function with a larger number between two values. my_max(x, y) Returns the larger one between the x and y parameters
2. Python built-in functions
1. All built-in functions
The Python interpreter contains a series of built-in functions. The following table lists the built-in functions in alphabetical order:
2. Rough Classification of Built-in Functions
Next, let's look at the built-in functions that are included in each category.
a. Mathematical Operational Classes
abs(x) |
Absolute value 1. Parameters can be integer or complex |
complex([real[, imag]]) | Create a plural |
divmod(a, b) | Quotient and Remainder, respectively Note: Integral and floating-point type can be used. |
float([x]) | Converts a string or number to a floating point number. If there are no parameters, 0.0 will be returned. |
int([x[, base]]) | Converting a character to an int type, base represents the base |
pow(x, y[, z]) | Returns the y power of x |
range([start], stop[, step]) | Generate a sequence, starting from 0 by default |
round(x[, n]) | Rounding |
sum(iterable[, start]) | Summation of sets |
oct(x) | Converting a digit to octal |
hex(x) | Converting integer x to hexadecimal string |
chr(i) | Returns the ASCII character corresponding to integer i |
bin(x) | Converting integer x to binary string |
bool([x]) | Convert x to Boolean type |
b. Collection class operations
basestring() |
Superclasses of str and unicode Can not be called directly, can be used as isinstance judgment |
format(value [, format_spec]) | Format output string The formatted parameter order starts at 0, such as "I am {0},I like {1}" |
unichr(i) | Returns unicode for a given int type |
enumerate(sequence [, start = 0]) | Returns an enumerable object whose next() method returns a tuple |
iter(o[, sentinel]) | Generate an iterator for an object, and the second parameter represents a separator |
max(iterable[, args...][key]) | Returns the maximum value in the collection |
min(iterable[, args...][key]) | Returns the minimum value in the set |
dict([arg]) | Create a Data Dictionary |
list([iterable]) | Converting one collection class to another |
set() | set object instantiation |
frozenset([iterable]) | Generate an immutable set |
str([object]) | Convert to string type |
Queue Set Sorting | |
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 returns an xrange object whose behavior is similar to that of the list. Similar, but only when needed to calculate the list value, when the list is large, this feature can save us memory. |
c. Logical Judgment
all(iterable) | 1. When all the elements in a set are true, they are true.
2. In particular, if an empty string returns to True |
any(iterable) | 1. An element in a collection is true when it is true 2. Specifically, if an empty string returns to False |
cmp(x, y) | If x < y, return negative number; x = y, return 0; x > y, return positive number |
d. reflection
callable(object) | Check whether the object is callable 1. Classes can be called 2. Instances cannot be called unless the _call_ method is declared in the class |
classmethod() | 1. Annotations to illustrate that this approach is a class approach 2. Class methods can be called either by class or by instance. 3. Class methods are similar to static methods in Java 4. There is no need for self parameters in class methods |
compile(source, filename, mode[, flags[, dont_inherit]]) |
Compile source to code or AST objects. Code objects can be executed by exec statements or evaluated by eval(). 1. Parameter source: String or AST (Abstract Syntax Trees) object. 2. Parameter filename: The name of the code file, passing some recognizable values if the code is not read from the file. 3. Parametric model: Specify the type of compiled code. You can specify'exec','eval','single'. 4. Parameters flag and dont_inherit: These two parameters are not introduced yet. |
dir([object]) | 1. Return the list of variables, methods and types defined in the current range without parameters. 2. With parameters, return the list of attributes and methods of parameters. 3. If the parameter contains the method _dir_(), the method will be called. When the parameter is an instance. 4. If the parameter does not contain _dir_(), the method will collect the parameter information to the maximum extent. |
delattr(object, name) | Delete the property of the object object object named name |
eval(expression [, globals [, locals]]) | Compute the value of expression |
execfile(filename [, globals [, locals]]) | The usage is similar to exec(), except that the parameter filename of execfile is the file name, and the parameter of exec is the string. |
filter(function, iterable) | Construct a sequence equivalent to [item for item in iterable if function(item)] 1. Parametric function: A function with a return value of True or False, which can be None 2. Parameter iterable: Sequence or Iterable Object |
getattr(object, name [, defalut]) | Get the properties of a class |
globals() | Returns a dictionary describing the current global symbol table |
hasattr(object, name) | Determine whether the object contains a feature named name |
hash(object) | If the object of the object is a hash table type, the hash value of the object of the object is returned. |
id(object) | Unique identifier of return object |
isinstance(object, classinfo) | Determine whether object is an instance of class |
issubclass(class, classinfo) | Judging whether it is a subclass |
len(s) | Return set length |
locals() | Returns the current list of variables |
map(function, iterable, ...) | Traversing through each element, performing function operations |
memoryview(obj) | Returns an object of memory mirror type |
next(iterator[, default]) | Similar to iterator.next() |
object() | Base class |
property([fget[, fset[, fdel[, doc]]]]) | The wrapper class accessed by attributes can be set up to access setter and getter through c.x=value, etc. |
reduce(function, iterable[, initializer]) | The merge operation starts with the first two parameters, 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) | Change an object into a printable format |
slice() | |
staticmethod | Declaring static methods is a comment |
super(type[, object-or-type]) | Reference parent class |
type(object) | Returns the type of the object |
vars([object]) | Returns the variable of the object, if no parameter is similar to the dict() method |
bytearray([source [, encoding [, errors]]]) | Returns a byte array 1. If the source is an integer, an initialized array with a length of source is returned. 2. If source is a string, the string is converted to a byte sequence 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 the same object as buffer interface, this object can also be used to initialize bytearray. |
zip([iterable, ...]) | It's really not understood, but only saw the changing aspects of the matrix. |
e.IO operation
file(filename [, mode [, bufsize]]) |
A file-type constructor that opens a file and creates a file if the file does not exist and the mode is written or appended. Adding'b'to the mode parameter will operate on the file in binary form. Adding'+'to the mode parameter will allow simultaneous reading and writing of files |
input([prompt]) |
Get user input It is recommended to use raw_input because this function will not capture the user's error input. |
open(name[, mode[, buffering]]) | Open file What's different from file? Recommended use of open |
Print function | |
raw_input([prompt]) | Set the input, which is processed as a string |
3. Detailed classification of built-in functions
These built-in functions are classified as follows:
- Mathematical operations (7)
- Type conversion (24)
- Sequential operations (8)
- Object operations (7)
- Reflection operation (8)
- Variable operations (2)
- Interaction (2)
- File operation (1)
- Compilation and execution (4)
- Decorators (3)
The specific analysis of each function is as follows:
(1) Mathematical operations
abs: Find the absolute value of the value
>>> abs(-2)
2
divmod: Returns the quotient and remainder of two values
>>> divmod(5,2) (2, 1) >> divmod(5.5,2) (2.0, 1.5)
max: Returns the maximum of elements or all parameters in an iterative object
>>> max(1,2,3) # The larger of the three afferent parameters 3 >>> max('1234') # Pass in an iterative object and take its maximum element value '4' >>> max(-1,0) # The default value is larger 0 >>> max(-1,0,key = abs) # When the absolute value function is introduced, the parameters will be calculated and then the larger one will be obtained. -1
min: Returns the minimum of elements or all parameters in an iterative object
>>> min(1,2,3) # The smaller of the three afferent parameters 1 >>> min('1234') # Pass in an iterative object and take its minimum element value '1' >>> min(-1,-2) # The default value is smaller -2 >>> min(-1,-2,key = abs) # When an absolute value function is introduced, the parameters will be evaluated for the absolute value and then the smaller one will be selected. -1
pow: Returns the power of two values or their modulus with the specified integer
>>> pow(2,3) >>> 2**3 >>> pow(2,3,5) >>> pow(2,3)%5
round: Rounding floating-point numbers
>>> round(1.1314926,1) 1.1 >>> round(1.1314926,5) 1.13149
Sum: The sum of each element in an iterative object whose element type is a numerical value
# Input Iterable Object >>> sum((1,2,3,4)) 10 # Element types must be numeric >>> sum((1.5,2.5,3.5,4.5)) 12.0 >>> sum((1,2,3,4),-10) 0
(2) Type conversion
bool: Create a new Boolean value based on the logical value of the incoming parameter
>>> bool() #Non-afferent parameters False >>> bool(0) #Number 0, null sequence equivalence False False >>> bool(1) True
int: Create a new integer based on the incoming parameters
>>> int() #When the parameters are not passed in, the result is 0. 0 >>> int(3) 3 >>> int(3.6) 3
float: Create a new floating point number based on the incoming parameters
>>> float() #When no parameters are provided, return 0.0 0.0 >>> float(3) 3.0 >>> float('3') 3.0
Complex: Create a new complex number based on the incoming parameters
>>> complex() #When neither parameter is provided, the complex number 0 is returned. j. 0j >>> complex('1+2j') #Input String Creates Complex (1+2j) >>> complex(1,2) #Input values create complex numbers (1+2j)
str: Returns the string representation of an object (to the user)
>>> str() '' >>> str(None) 'None' >>> str('abc') 'abc' >>> str(123) '123'
bytearray: Create a new byte array based on the incoming parameters
>>> bytearray('Chinese','utf-8') bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
bytes: Create a new immutable byte array based on the incoming parameters
>>> bytes('Chinese','utf-8') b'\xe4\xb8\xad\xe6\x96\x87'
memoryview: Create a new memory view object based on the incoming parameters
>>> v = memoryview(b'abcefg') >>> v[1] 98 >>> v[-1] 103
ord: Returns the integer corresponding to the Unicode character
>>> ord('a') 97
chr: Returns Unicode characters corresponding to integers
>>> chr(97) #The parameter type is an integer 'a'
bin: Converts integers to binary strings
>>> bin(3) '0b11'
oct: Converts integers into octal numeric strings
>>> oct(10) '0o12'
hex: Converts integers to hexadecimal strings
>>> hex(15) '0xf'
Tuple: Create a new tuple based on the parameters passed in
>>> tuple() #Create empty tuples without passing in parameters () >>> tuple('121') #Input an iteratable object. Use its elements to create new tuples ('1', '2', '1')
List: Create a new list based on the incoming parameters
>>>list() # Create an empty list without passing in parameters [] >>> list('abcd') # Pass in an iteratable object and use its elements to create a new list ['a', 'b', 'c', 'd']
dict: Create a new dictionary based on the incoming parameters
>>> dict() # When no parameters are passed in, the empty dictionary is returned. {} >>> dict(a = 1,b = 2) # You can pass in key-value pairs to create dictionaries. {'b': 2, 'a': 1} >>> dict(zip(['a','b'],[1,2])) # You can pass in a mapping function to create a dictionary. {'b': 2, 'a': 1} >>> dict((('a',1),('b',2))) # You can pass in an iterative object to create a dictionary. {'b': 2, 'a': 1}
set: Create a new collection based on the incoming parameters
>>>set() # Create an empty collection without passing in parameters set() >>> a = set(range(10)) # Input Iterable Objects, Create Collections >>> a {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
frozenset: Create a new immutable set based on the incoming parameters
>>> a = frozenset(range(10)) >>> a frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
enumerate: Create enumerated objects based on iterative objects
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) #Specify a starting value [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Range: Create a new range object based on the incoming parameters
Syntax:
- range(stop) starts from zero, adding 1 operation after each integer generation until stop (excluding stop)
- range(start, stop[, step]) starts with start and moves step after each integer is generated until stop (excluding stop, and step can be a negative integer)
Role: Used to create an iterative object (also known as an integer sequence generator) that generates a series of integers
Description: The object returned by range is an iterative object. It can be used in for statement.
>>> a = range(10) >>> b = range(1,10) >>> c = range(1,10,3) >>> a,b,c # Separate output a,b,c (range(0, 10), range(1, 10), range(1, 10, 3)) >>> list(a),list(b),list(c) # Separate output a,b,c Elements ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7]) >>>
iter: Create a new Iterable object based on the parameters passed in
>>> a = iter('abcd') #String Sequence >>> a <str_iterator object at 0x03FB4FB0> >>> next(a) 'a' >>> next(a) 'b' >>> next(a) 'c' >>> next(a) 'd' >>> next(a) Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> next(a) StopIteration
Slice: Create a new slice object based on the incoming parameters
>>> c1 = slice(5) # Definition c1 >>> c1 slice(None, 5, None) >>> c2 = slice(2,5) # Definition c2 >>> c2 slice(2, 5, None) >>> c3 = slice(1,10,3) # Definition c3 >>> c3 slice(1, 10, 3)
super: Create a new proxy object for child and parent relationships based on the parameters passed in
#Defining parent class A >>> class A(object): def __init__(self): print('A.__init__') #Defining subclasses B,inherit A >>> class B(A): def __init__(self): print('B.__init__') super().__init__() #super Calling parent class methods >>> b = B() B.__init__ A.__init__
Object: Create a new object object object
>>> a = object() >>> a.name = 'kim' # Attributes cannot be set Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> a.name = 'kim' AttributeError: 'object' object has no attribute 'name'
(3) Sequence operation
all: Determines whether each element of an iterative object is a True value
>>> all([1,2]) #Each element in the list has a logical value of True,Return True True >>> all([0,1,2]) #The logical value of 0 in the list is False,Return False False >>> all(()) #Empty tuple True >>> all({}) #Empty dictionary True
any: Determines whether elements of an iterative object are elements with True values
>>> any([0,1,2]) #The list element has a True,Then return True True >>> any([0,0]) #List elements are all False,Then return False False >>> any([]) #Null list False >>> any({}) #Empty dictionary False
filter: Filters elements of iteratable objects using specified methods
>>> a = list(range(1,10)) #Definition sequence >>> a [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> def if_odd(x): #Define odd number judgement function return x%2==1 >>> list(filter(if_odd,a)) #Odd numbers in screening sequences [1, 3, 5, 7, 9]
map: Use the specified method to act on the elements of each iteratable object passed in to generate a new iteratable object
>>> a = map(ord,'abcd') >>> a <map object at 0x03994E50> >>> list(a) [97, 98, 99, 100]
Next: Returns the next element value in an iteratable object
>>> a = iter('abcd') >>> next(a) 'a' >>> next(a) 'b' >>> next(a) 'c' >>> next(a) 'd' >>> next(a) Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> next(a) StopIteration #afferent default After the parameter, if the iteratable object still has elements that are not returned, the element values are returned in turn, and if all elements have been returned, the element values are returned. default Specifies the default value without throwing it StopIteration abnormal >>> next(a,'e') 'e' >>> next(a,'e') 'e'
reversed: Inverse Sequences Generate New Iterable Objects
>>> a = reversed(range(10)) # afferent range object >>> a # Types become iterators <range_iterator object at 0x035634E8> >>> list(a) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
sorted: Sort the iteratable objects and return a new list
>>> a = ['a','b','d','c','B','A'] >>> a ['a', 'b', 'd', 'c', 'B', 'A'] >>> sorted(a) # Default by character ascii Code sorting ['A', 'B', 'a', 'b', 'c', 'd'] >>> sorted(a,key = str.lower) # Convert to lowercase and sort again.'a'and'A'The same value.'b'and'B'Same value ['a', 'A', 'b', 'B', 'c', 'd']
zip: Aggregate elements of the same location in each iterator passed in, returning a new tuple-type iterator
>>> x = [1,2,3] #Length 3 >>> y = [4,5,6,7,8] #Length 5 >>> list(zip(x,y)) # Minimum length 3 [(1, 4), (2, 5), (3, 6)]
(4) Object operation
Help: Returns help information for the object
>>> help(str) Help on class str in module builtins: class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer | that will be decoded using the given encoding and error handler. | Otherwise, returns the result of object.__str__() (if defined) | or repr(object). | encoding defaults to sys.getdefaultencoding(). | errors defaults to 'strict'. | | Methods defined here: | | __add__(self, value, /) | Return self+value.
dir: Returns a list of attributes within an object or current scope
>>> import math >>> math <module 'math' (built-in)> >>> dir(math) ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
id: Unique identifier of the returned object
>>> a = 'some text' >>> id(a) 69228568 hash: Gets the hash value of the object >>> hash('good good study') 1032709256
Type: Returns the type of the object, or creates a new type based on the parameters passed in
>>> type(1) # Type of returned object <class 'int'> #Use type Function creation type D,Containing attributes InfoD >>> D = type('D',(A,B),dict(InfoD='some thing defined in D')) >>> d = D() >>> d.InfoD 'some thing defined in D'
len: Returns the length of the object
>>> len('abcd') # Character string >>> len(bytes('abcd','utf-8')) # Byte array >>> len((1,2,3,4)) # tuple >>> len([1,2,3,4]) # list >>> len(range(1,5)) # range object >>> len({'a':1,'b':2,'c':3,'d':4}) # Dictionaries >>> len({'a','b','c','d'}) # aggregate >>> len(frozenset('abcd')) #Immutable set
ascii: Printable table string representation of returned objects
>>> ascii(1) '1' >>> ascii('&') "'&'" >>> ascii(9000000) '9000000' >>> ascii('Chinese') #wrong ascii character "'\\u4e2d\\u6587'"
format: format display values
#The parameters that a string can provide 's' None >>> format('some string','s') 'some string' >>> format('some string') 'some string' #The parameters that can be provided by shaping values are 'b' 'c' 'd' 'o' 'x' 'X' 'n' None >>> format(3,'b') #Converting to binary '11' >>> format(97,'c') #Transformation unicode Character formation 'a' >>> format(11,'d') #Conversion to decimal '11' >>> format(11,'o') #Converting to octal '13' >>> format(11,'x') #Converting to hexadecimal lowercase letters 'b' >>> format(11,'X') #Convert to hexadecimal capital letters 'B' >>> format(11,'n') #and d equally '11' >>> format(11) #Default sum d equally '11' #Floating-point numbers can provide parameters such as 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None >>> format(314159267,'e') #Scientific counting, default reserve 6 decimal '3.141593e+08' >>> format(314159267,'0.2e') #Scientific counting, specifying the retention of two decimal places '3.14e+08' >>> format(314159267,'0.2E') #Scientific counting, designated to retain 2 decimal places, capitalized E Express '3.14E+08' >>> format(314159267,'f') #Decimal point counting method, default reserve 6 decimal '314159267.000000' >>> format(3.14159267000,'f') #Decimal point counting method, default reserve 6 decimal '3.141593' >>> format(3.14159267000,'0.8f') #The decimal point counting method, specifying the retention of 8 decimal places '3.14159267' >>> format(3.14159267000,'0.10f') #The decimal point counting method, specifying the retention of 10 decimal places '3.1415926700' >>> format(3.14e+1000000,'F') #Decimal point counting, infinity converted into large and small letters 'INF' #g The formatting is special and hypothetical. p In order to reserve the decimal number specified in the format, we first try to format it by scientific counting method and get the power exponent. exp,If-4<=exp<p,The decimal counting method is adopted and retained. p-1-exp Bit decimal, otherwise count by decimal count, and press p-1 Keep decimal digits >>> format(0.00003141566,'.1g') #p=1,exp=-5 ==> -4<=exp<p If not, count by scientific counting method, keep 0 decimal point. '3e-05' >>> format(0.00003141566,'.2g') #p=1,exp=-5 ==> -4<=exp<p If not, count by scientific counting method, keep 1 decimal point. '3.1e-05' >>> format(0.00003141566,'.3g') #p=1,exp=-5 ==> -4<=exp<p If not, count by scientific counting method, keep 2 decimal points. '3.14e-05' >>> format(0.00003141566,'.3G') #p=1,exp=-5 ==> -4<=exp<p If it is not established, it should be counted according to the scientific counting method, and 0 decimal points should be reserved. E Capitalize '3.14E-05' >>> format(3.1415926777,'.1g') #p=1,exp=0 ==> -4<=exp<p Set up, count by decimal number, keep 0 decimal point '3' >>> format(3.1415926777,'.2g') #p=1,exp=0 ==> -4<=exp<p Set up, count by decimal number, keep 1 decimal point '3.1' >>> format(3.1415926777,'.3g') #p=1,exp=0 ==> -4<=exp<p Set up, count by decimal number, keep 2 decimal points '3.14' >>> format(0.00003141566,'.1n') #and g identical '3e-05' >>> format(0.00003141566,'.3n') #and g identical '3.14e-05' >>> format(0.00003141566) #and g identical '3.141566e-05'
vars: Returns a dictionary of local variables and their values in the current scope, or a list of attributes of the object
#Acting on class instances >>> class A(object): pass >>> a.__dict__ {} >>> vars(a) {} >>> a.name = 'Kim' >>> a.__dict__ {'name': 'Kim'} >>> vars(a) {'name': 'Kim'}
(5) Reflection operation
_ import_: Dynamic import Module
index = __import__('index') index.sayHello()
isinstance: An instance that determines whether an object is an element of any class in a class or type tuple
>>> isinstance(1,int) True >>> isinstance(1,str) False >>> isinstance(1,(int,str)) True
issubclass: Determines whether a class is a subclass of any class element in another class or type tuple
>>> issubclass(bool,int) True >>> issubclass(bool,str) False >>> issubclass(bool,(str,int)) True
hasattr: Check whether an object contains attributes
#Definition class A >>> class Student: def __init__(self,name): self.name = name >>> s = Student('Aim') >>> hasattr(s,'name') #a Contain name attribute True >>> hasattr(s,'age') #a Do not contain age attribute False
getattr: Gets the attribute value of the object
#Definition class Student >>> class Student: def __init__(self,name): self.name = name >>> getattr(s,'name') #Existence attribute name 'Aim' >>> getattr(s,'age',6) #No attribute exists age,But the default value is provided and the default value is returned. >>> getattr(s,'age') #No attribute exists age,No default value is provided. Call error Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> getattr(s,'age') AttributeError: 'Stduent' object has no attribute 'age'
setattr: Set the property value of the object
>>> class Student: def __init__(self,name): self.name = name >>> a = Student('Kim') >>> a.name 'Kim' >>> setattr(a,'name','Bob') >>> a.name 'Bob'
delattr: Delete attributes of objects
#Definition class A >>> class A: def __init__(self,name): self.name = name def sayHello(self): print('hello',self.name) #Test attributes and methods >>> a.name 'Wheat' >>> a.sayHello() hello Wheat #Delete attribute >>> delattr(a,'name') >>> a.name Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> a.name AttributeError: 'A' object has no attribute 'name'
callable: Detecting whether an object can be invoked
>>> class B: #Definition class B def __call__(self): print('instances are callable now.') >>> callable(B) #class B Callable object True >>> b = B() #Calling class B >>> callable(b) #Example b Callable object True >>> b() #Call instance b Success instances are callable now.
(6) Variable operation
globals: Returns a dictionary of global variables and their values in the current scope
>>> globals() {'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>} >>> a = 1 >>> globals() #One more. a {'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
locals: Returns a dictionary of local variables and their values in the current scope
>>> def f(): print('before define a ') print(locals()) #Invariable in scope a = 1 print('after define a') print(locals()) #There is one in scope a Variable with a value of 1 >>> f <function f at 0x03D40588> >>> f() before define a {} after define a {'a': 1}
(7) Interaction
print: print out to standard output objects
Function: To output a series of values as strings to the standard output device, defaulting to the terminal.
Format: print (value,..., sep=', end=' n')
The keyword parameter of the option is:
Separator between two values of sep, default to a space
After the end output is completed, a character is automatically appended to the end of the stream, defaulting to the newline character'n'
>>> print(1,2,3) 1 2 3 >>> print(1,2,3,sep = '+') 1+2+3 >>> print(1,2,3,sep = '+',end = '=?') 1+2+3=?
Input: Read user input values
Function: Read a string from a standard input device (the end newline character will be deleted)
Format:
input('prompt string')
Explain:
Returns the input string (python 3 only)
'prompt string'can be null
>>> s = input('please input your name:') please input your name:Ain >>> s 'Ain'
(8) File operation
open: open the file using the specified pattern and code, and return the file read-write object
# t Read and write for the text. b Read and write for binary >>> a = open('test.txt','rt') >>> a.read() 'some text' >>> a.close()
(9) Compilation and execution
compile: compile strings into code or AST objects so that they can be exec statements to execute or eval to evaluate
>>> #Process statement usage exec >>> code1 = 'for i in range(0,10): print (i)' >>> compile1 = compile(code1,'','exec') >>> exec (compile1) 0 1 2 3 4 5 6 7 8 9 >>> #Simple evaluation expressions are used eval >>> code2 = '1 + 2 + 3 + 4' >>> compile2 = compile(code2,'','eval') >>> eval(compile2) 10
eval: Perform dynamic expression evaluation
>>> eval('1+2+3+4') 10
exec: Execute dynamic statement blocks
>>> exec('a=1+2') #Execution statement >>> a 3
repr: Returns the string representation of an object (to the interpreter)
>>> a = 'some text' >>> str(a) 'some text' >>> repr(a) "'some text'"
(10) Decorators
property: Decorator that labels attributes
>>> class C: def __init__(self): self._name = '' @property def name(self): """i'm the 'name' property.""" return self._name @name.setter def name(self,value): if value is None: raise RuntimeError('name can not be None') else: self._name = value >>> c = C() >>> c.name # Access attribute '' >>> c.name = None # Validation when setting properties Traceback (most recent call last): File "<pyshell#84>", line 1, in <module> c.name = None File "<pyshell#81>", line 11, in name raise RuntimeError('name can not be None') RuntimeError: name can not be None >>> c.name = 'Kim' # set a property >>> c.name # Access attribute 'Kim' >>> del c.name # Delete attributes, do not provide deleter It cannot be deleted. Traceback (most recent call last): File "<pyshell#87>", line 1, in <module> del c.name AttributeError: can't delete attribute >>> c.name 'Kim'
classmethod: Decorator that labels methods as class methods
>>> class C: @classmethod def f(cls,arg1): print(cls) print(arg1) >>> C.f('Class object calls class method') <class '__main__.C'> //Class object calls class method >>> c = C() >>> c.f('Class instance object calls class method') <class '__main__.C'> //Class instance object calls class method
Static method: Decorator labeled static method
# Defining static methods with decorators >>> class Student(object): def __init__(self,name): self.name = name @staticmethod def sayHello(lang): print(lang) if lang == 'en': print('Welcome!') else: print('Hello!') >>> Student.sayHello('en') #Class call,'en'Passed to lang parameter en Welcome! >>> b = Student('Kim') >>> b.sayHello('zh') #Class instance object call,'zh'Passed to lang parameter zh //Hello
3. Functional Programming
1. Anonymous function (lamba)
Role: Create an anonymous function object
Similar to def, but no function name is provided
Syntax:
lambda [parameter 1, parameter 2,...]: expression The content in [] can be omitted
Example:
def myadd(x, y): return x + y # The above functions can be rewritten to: myadd = lambda x, y: x + y print('2 + 3 =', myadd(2, 3))
Grammatical Description:
- lambda is just an expression that creates a function object
- When a lambda expression is invoked, the expression with a colon followed by (:) is executed and a reference to the result of the expression is returned.
- A lambda expression creates a function that contains only one "expression"
- lambda is simpler than function, and can be created and destroyed at any time, which is helpful to reduce the coupling degree of program.
2. Function as parameter
Functions are variables: Function names are variables, which bind a function when creating a function
Example:
def f1(): print("f1 Be called") fx = f1 fx() # Equate to f1()
A function is a parameter of another function:
Example:
def f1(): print("hello") def f2(): print('world') def fx(fn): print(fn) fn() # Who to call? fx(f1) # What is this statement doing? fx(f2)
Function is the return value of another function:
That is, another function can return a function.
Example:
# This example demonstrates that the function is the return value of the function. def get_fx(): s = input('Please enter the operation you want to do.: ') if s == 'Seeking maximum': return max elif s == 'Seeking minimum': return min elif s == 'Summation': return sum L = [2,4,6,8,10] print(L) f1 = get_fx() print(f1(L))
3. Return function (closure Closure)
Packing statements of built-in functions together with their execution environments results in objects called closures.
Closure must satisfy three conditions:
- There must be an embedded function
- Embedded functions must refer to variables in external functions
- The return value of an external function must be an embedded function
Example:
def outer(a): //Outer function b=10 def inner(): //Internal functions return a+b //Temporary variables of external functions are used in internal functions return inner //Application of Return Internal Function demo=outer(5) //demo A reference to an internal function demo() ## 15 def outer(n): //Outer function def inner(a): //Internal function, acceptance of parameters return a**n //Parameters for calling external functions return inner x=outer(2)(3) print(x) ## 9
When we call outer(5), the result of summation is not returned, but the reference of inner() function. When we call function demo(), the result of summation is calculated.
In this example, we define function inner() in function outer(), and internal function inner() can refer to parameters and local variables of external function outer(). When outer() returns function inner, relevant parameters and variables are stored in the returned function, which is called Closure. The program structure has great power. External functions find that their own temporary variables will be used in future internal functions. At the end of their own, they return to the internal function, while the temporary variables of the external function will be sent to the internal function to bind together. So the outer function is over and the temporary variable of the outer function can still be used when calling the inner function.
Modifying variables of external functions in internal functions: This variable can be declared with nonlocal keywords, indicating that the variable is not a variable in local variable space, and that it needs to be found in the upper variable space.
def outer(a): //Outer function b=10 def inner(): //Internal functions nonlocal b //To indicate that the variable is not a local variable, it is necessary to find the variable in the upper variable space. b=20 //Modifying Temporary Parameters of External Variables return a+b //Temporary variables of external functions are used in internal functions return inner //Returns a reference to an inner function demo=outer(5) //demo A reference to an internal function demo() ### 25
It is also important to note that in the process of using closures, once the external function is called, the reference of the internal function is returned. Although the internal function is opened once and then disappears after the execution of a function, there is only one closure variable in fact, and the same closure variable is used every time the internal function is opened.
def outer(a): //Outer function def inner(b): //Internal functions nonlocal a //To indicate that the variable is not a local variable, it is necessary to find the variable in the upper variable space. a=a+b //Modifying Temporary Parameters of External Variables return a //Temporary variables of external functions are used in internal functions return inner //Application of Return Internal Function demo=outer(2) //demo A reference to an internal function print( demo(3) ) ## 5 print( demo(4) ) ## 9
!!! When returning closures, keep in mind that the return function does not refer to any cyclic variables or variables that will change later.
4. decorator
a. Functional Decorator
Function decorator is a function decorated, a function passed in, and a function returned.
If we want to enhance the function of a function, but do not want to modify the definition of the function, this dynamic way of enhancing the function during code running is called Decorator. In essence, decorator is a higher order function of return function, and the input parameter is a function to be executed. It takes several more steps on the basis of closure.
For example, we now record the time before and after the function call, and then record the running time of the program. We usually think of adding timing code directly before and after the program, but this often needs to modify the definition of the function, so it is generally not used in this way.
def myfunc(): startT=time.time() #start time print("myfunc start.....") time.sleep(1) print("myfunc end....") endT=time.time() #End time msecs=(endT-startT)*1000 print("It costs to run the program. %f ms"%msecs) myfunc()
So, the decorator appeared. If we want to define a decorator that can record the running time of a program, we can define it as follows:
from functools import wraps def deco(func): @wraps(func) #Without that myfunc.__name__ The value becomes wrapper def wrapper(): startT=time.time() #The operation done before the function is executed print("Before the function is executed") func() print("After the function is executed") endT=time.time() #The operation done after the function is executed msecs=(endT-startT)*1000 print("It costs to run the program. %f ms"%msecs) return wrapper @deco # Amount to myfunc=deco(myfunc) def myfunc(): print("myfunc start.....") time.sleep(1) print("myfunc end....") myfunc() #Actually, it's in execution. wrapper()function,that is deco(myfunc).wrapper()
Grammar of Functional Decorator:
def decorator function name (parameter): Statement block return function object
The grammar of the decorated function:
@ Decorator function name
def function name (parameter list): Statement block
b.python built-in decorator
@ Static method: Class static method
The difference from member methods is that there is no self parameter and it can be invoked without instantiating the class
@ classmethod: Class method
The difference from the member method is that the first parameter received is not self (a pointer to a class instance), but cls (the specific type of the current class).
@ property: Attribute method
Convert a class method to a class attribute, read-only attribute
class A: def talk(): print("talk") A.talk() ###Can execute a=A() a.talk() ###Can not hold class A: def talk(self): print("talk") A.talk() ###Not enforceable a=A() a.talk() ###Can hold class A: @staticmethod def talk(): print("talk") A.talk() ###Can execute a=A() a.talk() ###Can execute
5. partial function
When the number of parameters of a function is too large to be simplified, a new function can be created by using functools.partial, which can fix some parameters of the original function, thus making it easier to call. Such a new function is called a partial function.
For example, the int() function can convert strings to integers. When only strings are passed in, the int() function defaults to decimal conversion.
>>> int('12345') 12345
But the int() function also provides additional base parameters with a default value of 10. If you pass in the base parameter, you can do N-ary conversion:
>>> int('12345', base=8) 5349 >>> int('12345', 16) 74565
When we need to convert a large number of binary strings, it is very troublesome to pass int(x, base=2) every time, so we can use funtools.
>>> import functools >>> int2 = functools.partial(int, base=2) >>> int2('1000000') 64 >>> int2('1010101') 85
6. High Order Function
A function that satisfies one of the following conditions is a higher-order function:
- A function accepts one or more functions as arguments
- Function returns a function
a.map
Map (func,* iterables) calculates a new iteratable object with functions and parameters for each element in the iteratable object. When the shortest iteratable object no longer provides data, the iterative object generation ends.
Example:
def pow2(x): return x**2 for x in map(pow2, range(1, 10)): print(x) //Built-in pow(x, y, z)=None) # Generate 1 ** 4 , 2**3 , 3 ** 2, 4 ** 1 for x in map(pow, range(1, 10), range(4,0,-1)): print(x) for x in map(pow, [2,3,5,7], [4,3,2,1], range(5, 10)): print(x)
b.filter
Format: filter(func, iterable)
Function: Filter data in iterable, which returns an Iterable object that filters Iterable
Description: Function func evaluates each element, returns False to discard the data, and returns True to retain the data.
Example:
def isodd(x): # Judgment of this function x is odd return x % 2 == 1 for x in filter(isodd, range(10)): print(x) even = [x for x in filter(lambda x: x%2==0, range(10))]
c.sorted
Function: Sort the data of the original iterative object and generate the sorted list
Format: sorted(iterable, key=None, reverse=False)
Explain:
- iterable iteratable object
- The key function is used to provide a reference value, which will be used as a basis for sorting.
- The reverse flag is used to set whether to sort in descending order or not.
Example:
L = [5, -2, -4, 0, 3, 1] L2 = sorted(L) # L2 = [-4, -2, 0, 1, 3, 5] L2 = sorted(L, reverse=True) L3 = sorted(L, key=abs) # L3 = [0, 1, -2, 3, -4, 5] # Reflection: names = ['Tom', 'Jerry', 'Spike', 'Tyke'] sorted(names) # What if you want to sort the names in ascending order of length? L4 = sorted(names, key=len)
D. reduce (non-built-in higher-order function)
Reduc () Acts a function on a sequence [x1, x2, x3,...]. This function must accept two parameters. Reduc continues the cumulative calculation of the result and the next element of the sequence and returns an integer. The effect is: reduce (f, [x1, x2, x3, x4]) = f (f (x1, x2), x3, x4)
>>> from functools import reduce >>> def fn(x, y): ... return x * 10 + y ... >>> reduce(fn, [1, 3, 5, 7, 9]) 13579
IV. Custom Functions
1. Parametric transfer
a. Location parameter transfer
The corresponding relationship between actual parameters and formal parameters is corresponding in order of position.
Syntax:
def function name (formal parameter 1, formal parameter 2,...): Statement block
Hint:
def myfun(a, b, c): pass myfun(1, 2, 3)
Explain:
Matching of Real and Formal Parameters Transferred by Position
The number of arguments must be the same as the number of formal parameters.
1) Sequence transfer:
Sequential parameterization refers to the transfer of parameters by position after the sequence is disassembled by * in the process of function call.
Example:
def myfun(a, b, c): pass s = [1, 2, 3] myfun(*s) # * Express the s Open s2 = "ABC" myfun(*s2)
2) asterisk tuple parameters:
Syntax:
def function name (* tuple parameter name): Sentence
Function: Collect polygamous location data
Description: Tuple parameters are usually used:'args'
For example, see:
def func(*args): print("The number of parameters is:", len(args)) print('args =', args) func(1,2,3,4) func("hello", "world", 1, 2, 3)
b. Key word reference:
Keyword parametric refers to assigning parameters according to their names.
Arguments and formal parameters are matched by name
Example:
def myfun(a, b, c): pass myfun(b=22, c=33, a=11) # Equate to myfun(11,22,33) myfun(c=3, b=2, a=1)
Explanation: References and formal parameters can be matched out of position.
1) Dictionary keyword reference:
Reference refers to a dictionary which is disassembled by ** and then transmitted by keywords.
Explain:
- The key name and the formal reference name of the dictionary must be the same.
- The dictionary key name must be a string
- The key name of the dictionary should exist in the form parameter
Example:
def myfun(a, b, c): pass d = {'c': 33, 'b': 22, 'a': 11} myfun(**d) # Disassemble the dictionary and pass it on
2) Named keyword parameters:
Syntax:
def function name (*, named keyword parameter): Sentence or def function name (* args, named keyword parameter): Sentence
Effect:
All parameters must be passed by keyword or dictionary keyword.
For example, see:
def fn(*, d, e): print("d=", d) print("e=", e) fn(d=100, e=200) # Legitimate call # fn(1, 2) # Illegal. No position reference is allowed. # fn(1, 2, d=100, e=200) def fm(*args, d, e): print(args) print('d=', d) print('e=', e) fm(1, 2, d=100, e=200) fm(*"AB", **{'e': 20, 'd':10})
3) Double asterisk dictionary parameters:
Syntax:
def function name (** dictionary parameter name): Sentence
Function: Collect multiple keyword references
Description: Usually the dictionary's formal name is "kwargs"
For example, see:
def func(**kwargs): print("The number of keyword parameters is:", len(kwargs)) print("kwargs =", kwargs) func(name='tarena', age=15) func()
c. Default parameters of functions
Explain:
1. Default parameters must exist from right to left. If a parameter has default parameters, all parameters on its right must have default parameters.
def test(a, b=10, c): # <---It's wrong. pass
2. The default parameters can be zero or more, or even all of them have default parameters.
Syntax:
def function name (formal parameter 1 = default argument 1, formal parameter 2 = default argument 2,...): Sentence
Example:
def info(name, age=1, address="Not filled"): print(name, "This year", age, 'year, The family address is:', address) info('tarena', 15) info('Wei Wei', 20, 'Chaoyang District of Beijing City') info('petty thief')
d. Comprehensive Parameter Transfer of Functions
Functional parametric transfer mode, which can be arbitrarily combined under the condition that the formal parametric energy can only be matched to the corresponding parameters.
Example:
def myfun(a, b, c): pass myfun(100, *[200, 300]) # Correct myfun(*'AB', 300) # Correct myfun(100, c=300, b=200) # Correct myfun(1, **{'c': 3, 'b': 2}) # Correct myfun(**{'c': 3, 'b': 2}, a=1) # Correct myfun(b=2, c=3, 1) # error,I'm not sure who I'm going to give.?
Explain:
- Default parameters, position parameters, asterisk tuple parameters, named key parameters and double star dictionary parameters can be mixed.
- In the process of parameter transmission, the position parameter is first transmitted, and then the keyword parameter is transmitted.
- The order of function parameters from left to right is: position parameter - > asterisk tuple parameter - > named key parameter - > double asterisk dictionary parameter.