python insight into functions

1, Partial function [understand]

Default parameter: it can reduce the difficulty of function call

Partial function: a function that does some control over function parameters

Note: the partial function does not need to be customized. You can directly use [system function]

Code demonstration:

# int() converts other data types to integer (hexadecimal) by default
print(int("123"))  # 123

# The int() function also provides a second parameter, base, to control the conversion to hexadecimal
print(int("123",base = 8))   # 83 (octal number)
print(int("110",base = 2))   # 6

import functools  # Introducing functools module
# The system provides functools Partial can create a partial function
int2 = functools.partial(int,base = 8)
print(int2("123"))    # 83

'''
Partial functions are mainly used for built-in functions,When the built-in functions can not meet some of our needs,We can generate a new function based on this built-in function(Partial function),The two functions can implement different requirements.
'''

2, Closure [Master]

If another function is defined inside a function, the external function is called an external function and the internal function is called an internal function

If an internal function is defined in an external function and the return value of the external function is an internal function, it constitutes a closure, then this internal function is called a closure

Conditions for realizing function closure:

1. Must be a nested function

2. The internal function must refer to a variable of an external function defined in a closed range, ---- the internal function refers to an external variable

3. The external function must return the internal function

Code demonstration:

# Closure: if an internal function is defined in an external function and the return value of the external function is an internal function, it constitutes a closure, then this internal function is called a closure

# The simplest closure
# External function
def outer():
    # Internal function
    def inner():
        print("lala")
    return inner  # Return the inner function
fn = outer()    # FN = = = = > inner function
fn()    # It is equivalent to calling the inner function to output lala


# Internal functions use variables of external functions
def outer1(b):
    a = 10
    def inner1():
        # Internal functions can use variables of external functions
        print(a + b)
    return inner1
fun1 = outer1(12)
fun1()

'''
be careful:
    1.When the closure is executed,The current operating environment can still be saved
    2.Closures can get different effects according to the local variables of the external scope,Similar to configuration function,Similarly, we can modify external variables,Closures implement different functions according to changes in variables.
    Application scenario: Decorator
'''

3, Scope of variable

1. Causes

Variable scope: the range within which variables can be accessed

Variables in the program can not be accessed in any statement. The access rights depend on where the variable is defined

Branching statement if.. in python else if.. And loop for do not have the problem of variable scope

if 5 > 4:
    a = 11
print(a)

for i in range(10):
    b = 32
print(b)
# In the branch structure, if if.. There is no scope problem in esle and for in loops Outside of them, you can directly access the variables defined inside

def fn():
    c = 99
# print(c)  # name 'c' is not defined

2. Division of scope of action

Local scope: L [local]

Function scope: E [Enclosing] defines variables in functions outside closures

Global scope: G [global]

Built in scope: B [build in]

Code demonstration:

def fn():
    c = 99
# print(c)  # name 'c' is not defined
1.Variables defined inside a function cannot be accessed outside the function.

# Global scope:
num1 = 12    # Global scope, which can be accessed directly inside and outside the function
def test():
    num2 = 87  # Function scope
    print(num1)
    # print(num3)   # name 'num3' is not defined
    def inner():
        num3 = 55   # Local scope
        # In internal functions, you can access global scope \ function scope \ local scope variables
        print(num1,num2,num3)
    return inner
test()
print(num1)
# print(num2)

fn = test()
fn()

n = int("28")   # The scope of builins built-in function when called, which is defined by the python interpreter

summary:
    1. In branch structure if.. if..esle  And in circulation for in There is no scope problem.Outside of them, you can directly access the variables defined inside.
    2.The scope is mainly reflected in the function, Variables defined inside a function cannot be accessed outside the function.
    3.Variables outside the function can be accessed inside the function.

3. Global and local variables [Master]

Global variables: define variables outside functions

Local variables: define variables inside functions

Note: local variables can only be used in the current function they are declared, while global variables can be used throughout the program

5. Use of global and nonlocal keywords [Master]

Usage scenario: when the internal Scope [local scope, function scope] wants to modify the scope of the global variable

1.global

Code demonstration:

num = 11
def test():
    num = 78
    print(num)
test()    # 78
print(num)  # 11

# If you want to modify a global variable inside a function, you need to use the global keyword
num1 = 11
def test1():
    # Change the declared variable inside the function into a global variable through the global keyword
    global num1
    num1 = 75
    print(num1)
test1()   # 75
print(num1)  # 75

2.nonlocal

Code demonstration:

# The nolocal keyword is mainly used in closure functions  

# The nolocal keyword is used in closure functions
x = 15  # global variable
def outer():
    x = 19
    def inner():
        # x = 23
        # global x   # x = 15 is used
        nonlocal x  # The variable used in this case is x = 19
        x += 1
        print("inner:",x)
    return inner

# The closure will save the current running environment
test = outer()
test()   # 20
test()   # 21
test()   # 22

num = 11
def demo():
    print(num)
demo()   # 11
demo()   # 11
demo()   # 11

4, List generation and generator [Master]

1. List generation / list derivation

list comprehension

System built-in method for creating list

Disadvantages of range(start,end,step): generally, the generated list is an equal difference sequence

Code demonstration:

# The most basic list
# 1. Generate all numbers between 1-10
list1 = list(range(1,11))
print(list1)

# Requirements: generate a list by program [1,4,9,16,25]
#The first method: use the original method to generate
list2 = []
for i in range(1,6):
    list2.append(i ** 2)
print(list2)

# The second method: use list generation
list3 = [i**2 for i in range(1,6)]
print(list3)   # [1, 4, 9, 16, 25]

# Use the list generator to generate all odd numbers between 1-10
list4 = [i for i in range(1,11) if i % 2 == 1]
print(list4)

# Use the list generator to generate all odd numbers between 1-10 and divisible by 3
list5 = [i for i in range(1,11) if i % 2 == 1 and i % 3 == 0]
print(list5)

# Using double loops in list generators
list6 = [i + j for i in "xyz" for j in "987"]
print(list6)

# Dictionary generation: (understand)
dict1 = {i:i*i for i in range(1,6)}
print(dict1)

# Set generating formula: (understand)
set1 = {i*i for i in range(1,6)}
print(set1)

2. Generator

generator

next()

Code demonstration:

Definition generator: You just need to generate the list[] change into() that will do
g = (i ** 2 for i in range(1,10))
print(g)
print(type(g))  #<class 'generator'>
# The data obtained by the generator cannot be output directly. If you want to access the data inside, you must use next() to traverse. Each time you call next(), you will output one data
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
# After traversing the data in the generator through next(), and then calling next(), StopIteration will appear
# print(next(g))   # StopIteration

# Application scenario of generator:
'''
When infinite data needs to be generated,General use generator.   If you use a list to generate infinite numbers,It takes up a lot of space,inappropriate.
'''

# Generator related function yield
'''
1.yield Exist in function,When there is a yield key word,The normal function becomes a generator function.
2.Calling generator functions does not execute code,Need to use next
3.You can constantly return values inside a function,However, the execution of the function will not be terminated(And return Different)
4.Every call next in the future,The program will yield Pause at
'''

def test(m):
    print("m=",m)
    yield m * 2
    print("m+1=",m+1)
    yield (m + 1) * 2
    print("m+2",m+2)

g = test(23) # If the keyword yield is added to the ordinary function test, the function becomes a generator function, and the direct call will not be executed
print(type(g))   # <class 'generator'>
print(next(g))    # Function execution pauses at the first yiled
print(next(g))    # Function execution pauses at the second yiled

5, Iterator [Master]

1. Iteratable object

Iteratable object [entity]: an entity that can directly act on the for loop [iteratable]

Data types that can act directly on the for loop:

​ a.list,tuple,dict,set,string

b.generator [() and yield]

isinstance: judge whether an entity is an iteratable object

Code demonstration:

How to import modules:
    First kind: import Module name
    Second:from Module name import function
from fib import fibonacci   Indicates import fib In the module fibonacci function

# Using iteratable objects requires importing collections abc
from collections.abc import Iterable

# Determine whether an entity is an iteratable object through isinstance 	    The return value is bool type, True or False

from collections.abc import Iterable
# Iteratable object: an entity that can be traversed by a for loop is an iteratable object

print(isinstance([],Iterable))   # True
print(isinstance((),Iterable))   # True
print(isinstance({},Iterable))   # True
print(isinstance("loha",Iterable)) # True
# generator 
print(isinstance((i for i in range(1,10)),Iterable))  # True

# Lists \ tuples \ dictionaries \ strings \ generators are all iteratable objects

print(isinstance(11,Iterable))  # False
print(isinstance(True,Iterable))  # False

# Integer \ floating point \ Boolean types are not iteratable objects

2. Iterator

Iterator: it can not only act on the for loop, but also be traversed by the next function [continuously call and return an element until the last element is traversed, then StopIteration appears]

So far, only generators are iterators

Conclusion: iterators are certainly iteratable objects, but iteratable objects are not necessarily iterators

isinstance: determines whether an entity is an iterator

Code demonstration:

from collections.abc import Iterator

# Iterator: an entity that can be traversed by either the for loop or the next function is called an iterator
# Currently, only generators are iterators

# Use isinstance() to determine whether an entity is an iterator

print(isinstance([],Iterator))  #False
print(isinstance((),Iterator))  #False
print(isinstance({},Iterator))  #False
print(isinstance("loha",Iterator))  #False
print(isinstance(11,Iterator))  #False
print(isinstance(False,Iterator))   #False

# Only generators are iterators
print(isinstance((i for i in range(1,10)),Iterator))  # True

3. Conversion between iteratable objects and iterators

You can convert iteratable objects to iterators: iter()

Code demonstration:

although list tuple str dict set These iteratable objects cannot be used next() Function traversal,But you can pass iter() Function to convert an iteratable object to an iterator.
# Convert iteratable object to iterator: iter()
list = [12,4,5,78]
# print(next(list))   # 'list' object is not an iterator
list1 = iter(list)   # Convert list to iterator
print(next(list1))   # 12
print(next(list1))   # 4
print(next(list1))   # 5
print(next(list1))   # 78

Summary:

a. all objects that can act on the for loop are of iteratable type

b. all objects that can act on the next function are Iterator type

c.list/tuple/dict/set/string are not iterators. You can get an Iterator object through iter()

Added by Gaia on Fri, 14 Jan 2022 17:49:43 +0200