Python Learning-functions
Tags: python functions
Directory
[TOC]
I. Processing of documents
Python's built-in function, open, provides the ability to manipulate files. The open function invokes the OS's system interface to get a class file Object F, which will be used as an identifier for the file operation. The file processing is divided into read and write from the behavior action. From the data types of operations, file processing is divided into manipulation strings and manipulation of binary data.
1. Read the file
withopen‘r‘, encoding=‘utf-8‘as f: = f.read()
Attention:
: 1, use with to properly handle the file closure problem.
2, given the File_path is the path of the file, Python default current directory (relative path), you can also give the absolute path, but the path under Windows to pay attention to \
the problem.
3, ‘r‘
indicates the read mode, if used ‘rb‘
means to use the Read binary mode, the difference is that the ‘r‘
mode will use the character encoding specified by the encoding parameter to decode the file, and convert to Unicode into memory as a str type exists, and ‘rb‘
instead of decoding, the binary data on the hard disk is read directly into memory as the bytes type exists.
4, the use of ‘r‘
more suitable for the need to perform explicit string operations on the content of the file, there is a need to present content needs. Use is ‘rb‘
more suitable for non-explicit operation of data, such as direct transmission, compression, etc., do not need to show the content to the user.
5, read
, readline
, readlines
respectively: read the entire file as a string, read a line as a string, read all the rows and return a list of columns.
2. Writing files
withopen‘w‘, encoding=‘utf-8‘as f: f.write(msg)
Attention:
: 1, the usage ‘w‘
mode will first look for the existence of this file, if it does not exist the new, if present, will empty all the contents of the original file.
2. Use write
a function to write to a file, which msg
should be a str
type.
3. File Operation function
File_path= ' text.py ' with Open(File_path,' w+ ', encoding=' Utf-8 ') asF:Print(F.fileno ())# Gets the index value of the file object in the kernelF.write (' Hello, World ')# Write DataF.flush ()# Force the contents of the cache to be brushed into the hard disk without closing the fileF.seek (0)# Move seek to the beginning Print(' Here's the data ', F.read ())# Read All content Print(F.readable ())# is readable Print(F.writable ())# Is it possible to write Print(F.seekable ())# Whether to move seekF.seek (0) F.truncate ()# Start at the end of the file from seek Print(' no data here ', F.read ())# Read Content Print(F.tell ())# Get current seek position
4. Precautions
- [x] Use
+
to extend the original file processing mode, for example w+
, r+
.
- [x] The operation of the file should pay particular attention to the current seek position, and the seek position will move with the read and write.
- [x] The file object F can be iterated, i.e.
for line in f
, can fetch one row at a time, similar readline
.
- [x] The function that can be used
charset
detect
to infer the encoding format of the binary data.
- [x] Use
a
, ab
mode to append content to the file, when using this mode, seek will automatically move to the end of the file.
- [x] Use the
seek(0)
function mate truncate()
function to complete the file emptying operation.
- The [x]
os
module provides many functions for working with files and directories.
- [x] All direct changes to the hard drive data will overwrite the current content, cannot move directly to the location, must be read to the content, modify the content, write to the hard disk way.
Second, function basis
Functions are the first class of objects in Python, that is, functions can be assigned as variables. Function names are references to function objects, which are not much different from normal variables, such as numeric objects that can be arithmetic, objects of set types can be iterated, and function objects can be executed. The function object holds the execution code and the execution context, each time the function is executed in memory to open a new function stack to save the function of the execution context, and then execute the function object code, once the function is completed will return the result of the function execution, and destroy the function stack, Thus ending the operation of a function.
1. Function body
The function body is used to define the code when the function executes, and the code in the function body is saved by the function object and executed when the function is called. The function is ()
called.
2. Input
A function can be thought of as a small program or subroutine, a micro-model of a computer that can accept input from a caller. The caller's input is different, the function executes the procedure and the result is also different, so although the code in the function body is pre-defined, but the caller can use different input to achieve different execution effect. The formal parameter of a function is a variable used to receive changeable input values.
3. Output
The function must have an output, even if there is no explicit declaration return
statement, which is added on the last line of the execution code return None
. The output of the function is used to represent the execution result of this function, regardless of whether the function requires output to the caller, and the output is required to be provided, even if it is provided None
. The general caller uses the output of the function to determine the result of the execution, and can make certain decisions about the execution of the external function through the output.
4. Local variable/variable scope
Because the execution context of a function is present in the function stack, and the function stack is destroyed after it is executed, all variables defined during the run of the function are called local variables, because these variables live in this function stack. You can locals()
get the local variable namespace content in the function stack of the current function by function during function run. Because variables exist only in the function stack, the scope of these variables is only valid during function execution. Once the function is executed, the address of the variable in the function stack cannot be accessed unless you explicitly return these variable addresses .
5. Anonymous function
The so-called anonymous function, which is a function without a function name, is exactly equivalent to the following two declarations:
=2 # 声明对象2,名字是a2 # 声明无名对象2#===============def f(): # 声明有名对象函数, 名字是f print(‘hello‘)lambda x:print(‘hello‘) # 声明无名对象函数 --> 匿名函数
Anonymous functions are generally mates, and other high- map
filter
reduce
order functions are used, when anonymous functions are input to other functions.
6. Function call
The execution of each function depends on the corresponding function stack, and even if the python
program does not define any functions, the program runs and relies on the top-level function stack to provide the global namespace. When a function is called, cpu
the code execution perspective will jump from the current function to the memory address of the other function, and once the function is executed, cpu
the code execution perspective will return to the next code address of the main key function. The keynote function obtains the return value of the function being tuned.
7. Namespace LEGB
local
The namespace where the current function resides
enclosing
Nested functions in the namespace, from son to father to Grandpa's search chain
global
Global namespace, which is the namespace of the module
builtin
Built-in namespaces, the upper level of the module, define all the built-in functions and variables
The detection sequence is:L --> E --> G --> B --> 报错
8. Function parameter Unpacking
The *args and **kw in the function provide an understanding of the package, args represents the tuple, and kw represents the dictionary, which can be used:
def show(a, b): print= (1,2)show(*x)#=========def show(a=1, b=2): print= {‘a‘10‘b‘20}show(**x)
9. Recursion
The so-called recursion, which is called by the function call itself, will generate and infinitely call itself like infinite loops. Each invocation of the function needs to create a function stack, and since the keynote function is not executed, the function stack of the keynote function will not be destroyed, but will wait for the function to return the result. With infinite recursion, a new, tuned function stack is generated indefinitely, preserving the keynote function stack, which results in a function 栈溢出
. python
the function stack is set to the maximum 1000
layer.
Recursive stop conditions must be set using recursion, just as you would use loops to set the loop exit condition.
Recursion makes it easy to solve some of the problems that need to be called constantly, but the recursive efficiency itself is not high, as it is necessary to create new function stacks and destroy function stacks without stopping.
Three, built-in functions
Print(dir(List))# View a list of all property names for an objectPrint(Sorted([233, the, Wu, About, About, the, the]))# Sort the sequence to return the new list objectPrint(Eval(' 3 + 5 '))# Execute string code, get return value, cannot execute assignment, etc. change program contents statementexec(' A = 2 ')# Executes multiple lines of string, the return value is always none, but can perform assignment and so on change the contents of the program statementPrint(a)Filter(LambdaX:x%2==0, [ the, the, Wu, Wu, About,6,2,2,3, the])# Perform sequence filteringMap(LambdaX:Str(x), [2334, the,4,5])# Execution sequence elements Unified processing fromFunctoolsImport ReduceReduce(LambdaX, y:x+Y, [ at, the, the, $,5, About])# Perform sequence regression cumulative operationsPrint(' msg is here ',' another msg ', Sep='! ', end='\ n!!!!\ n')# The parameters of the print function are usedF= LambdaX:2callable(f)# Whether the object can be called judgmentPrint(List(Zip([ at, at, +, +], [4, the, +, the])))# A package operation that performs multiple sequences, truncates the sequence to the shortest possible, and packages Narimoto groups with multiple sequence elements
Iv. function Advanced 1, closed package
Once the function is defined, the execution code and context are saved to the function object. The context environment retains the outer nested context in addition to preserving the current level of the environment. Once this function is returned as a variable to an external function, the outer function can be called at any time, and when called, the inner layer function can access the context in the previously reserved nested function. This is the case: closures, that is, the execution of code and execution environment together, once executed, you can use nested context. Closures can be used to preserve the variable state of nested functions.
def outer(): =20 def inner(): print(a) return= outer()f() # 执行inner的时候,可以访问到a = 20
2. Adorner function
Because of the nature of closures, functions can be extended to function, without modifying the original function code under the premise of adding additional functionality. The adorner is also a high-order function that takes the original function as input, functions the original function and returns a new function with the same name as the original function. Once the new function is executed, the original function function and the extension function will be executed together.
func_map = {}def register(key): def wrapper_outer(func): def wrapper_inner(*args, **kw): result = func(*args, **kw) print(‘扩展功能‘) return result func_map[key] = wrapper_inner return wrapper_outer return wrapper_outer@register(‘show‘)def show(msg): print(‘this is show msg:‘, msg)msg = ‘hello, world‘func_map[‘show‘](msg)
3. Generator function
The generator function can be designed to never destroy the function stack, but it can be switched to the function stack through yield with the keynote function. The biggest benefits of generator functions are the following:
1. Lazy calculation, the generator needs to be executed manually next
or the send
generator function code will be executed
2. Can be carried out with the main function 函数栈切换
, high efficiency, serial lock-free, non-variable security issues
3. The generator function can pass the yield
return value, the keynote function by send
sending the value, the two can interact
4. Can be used to implement协程
Log_path= ' Xxx.log 'defLogger_generator (Log_path): Log_count= 0 with Open(Log_path,' W ', encoding=' Utf-8 ') asF:# Prepare log file, pre-empty content PassMsg= yield ' OK ' while True:# always execute ifMsg== ' Stop ':return ' Stop ' # Throw Stopiteration, the keynote function to try Else: Log_count+= 1Msg= ' # [{Log_count}] --{msg}\ n'.format(Log_count=Log_count, MSG=Msg# Prepare log information with Open(Log_path,' A ', encoding=' Utf-8 ') asF:# log to fileF.write (msg) log_summary= '%dinformations has been logged! ' %Log_count# Prepare log summary informationMsg= yieldLog_summary# Returns the current log summary information while waiting for the keynote to send a new log messageLogger=Logger_generator (Log_path) logger.send (None)Print(Logger.send (' User login '))Print(Logger.send (' User password modification '))
V. Several technical questions 1, unpacking
Li=[1,2,3,4,5]first,*Mid, last=LiPrint(First, Mid, last) first, second,*_=LiPrint(First, second, _) A, B,*C= Range(5)Print(A, B, c) dic1={' A ':1}dic2={' B ':2}dic3={**Dic1,**DIC2}Print(DIC3) DIC={' name ':' Hz ',' age ': -,}msg= ' name is:{Name}, age is:{Age}'.format(**DiCPrint(msg)
1. Use unpacking to make your code more concise
2. *
and **
respectively for unpacking sequences and dictionaries
3. Use *_
to host unwanted values, _
variables can also be used
2. Value Exchange
The following two are equivalent:
=2=33=== tempprint(a, b)#==========3=44= b, aprint(a, b)
Python's value exchange automatically handles temp temporary variables for you
3. Default parameter traps
=20def show(x=a): print=30show()show(a)print(‘#=========‘)def show(x=[]): x.append(99) print(x)show()show()show()
The result is:
2030#=========[99][9999][999999]
1. Default parameters fixed a reference object when the function was compiled
2. If not explicitly supplied, show(a)
the original fixed object will be printed20
3. If the default parameter points to a mutable object, because a Mutable object can modify the value, it causes the non-expected result, such as[99,99,99]
4. The default parameter must point to the immutable object, and when calling the function, provide the value as explicitly as possible
4, the generator in-depth understanding
Benefits of the generator:
- [x] Save calculation rules, algorithms, memory space, and calculate at any time.
- [x] efficient function stack switching, generator functions can also be nested multi-layered, multiple
yield
offers more flexible switching control
- [x] The context environment in the Save generator function is not destroyed and can be restored using these variable values as soon as it is switched in
- [x] can collaborate with the keynote function or other sub-layer generator functions to complete program execution
- [x] Use
send
, next
yield
to provide message, signal interaction
- [x] can implement the process , efficient serial execution, non-variable security issues, no need to lock
Python Learning-functions