function

Definition of a function

  • Functions begin with the def keyword, followed by the function name and parentheses ().
  • The code executed by the function starts with a colon and is indented.
  • Return terminates the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None

grammar

def functionname (parameters) :
       "Function docstring"
        functionsuite
        return [expression]
Copy the code

Function call

def printme(str) :
    print(str)


printme("I'm going to call a user-defined function!")  I want to call a user - defined function!
printme("Call the same function again")  Call the same function again
temp = printme('hello') # hello
print(temp)  # None
Copy the code

Function of the document

def MyFirstFunction(name) :
    "Name is a parameter during function definition."
    Because Ta is just a form that takes a parameter position
    print('The {0} passed in is called an argument because Ta is a concrete parameter value! '.format(name))


MyFirstFunction('The Old Horse of Procedural Life')  
The code passed in is called an argument, because Ta is a concrete parameter value!

print(MyFirstFunction.__doc__)  
Name is the parameter in the function definition

help(MyFirstFunction)
# Help on function MyFirstFunction in module __main__:
# MyFirstFunction(name)
Name is the parameter in the function definition
Copy the code

Function parameters

  1. Positional argument
def functionname(arg1) :
       "Function docstring"
       functionsuite
       return [expression]
Copy the code
  • Arg1 – positional arguments that are fixed in position when a call function is called
  1. Default argument (Default argument)
def functionname(arg1, arg2=v) :
       "Function docstring"
       functionsuite
       return [expression]
Copy the code
  • Arg2 = v – Default argument = default, the value of the default argument is taken as the default if not passed in when the function is called.
  • The default parameter must be placed after the positional parameter, otherwise the program will report an error.
  • Python allows functions to be called in a different order than when they are declared, because the Python interpreter can match parameter values with parameter names
  1. Variable argument
def functionname(arg1, arg2=v, *args) :
       "Function docstring"
       functionsuite
       return [expression]
Copy the code
  • * ARgs – Variable arguments, which can be from zero to any, automatically assembled into tuples.
  • The variable name marked with an asterisk (*) holds all unnamed variable arguments
  1. Keyword argument
def functionname(arg1, arg2=v, args, *kw) :
       "Function docstring"
       functionsuite
       return [expression]
Copy the code
  • **kw – keyword argument, can be from zero to any, automatic dictionary assembly

The similarities and differences between “variable arguments” and “keyword arguments” are summarized as follows:

  • Mutable arguments allow zero to any parameters to be passed in, which are automatically assembled into a tuple when the function is called.
  • Keyword arguments allow zero to any arguments to be passed, which are automatically assembled as a dict inside the function
  1. Named keyword argument (name keyword argument)
def functionname(arg1, arg2=v, args, *, nkw, *kw) :
       "Function docstring"
       functionsuite
       return [expression]
Copy the code
  • *, NKW – Named keyword parameter, the keyword parameter that the user wants to enter, defined by a delimiter * before NKW
  • If you want to restrict the names of keyword arguments, you can use named keyword arguments
  • When using named keyword arguments, be careful not to miss parameter names
  • The argument name NWK is not written, so 10 is treated as a “positional argument”. The original function only had one positional function. Now two positional functions are called, so the program will report an error
  1. Parameter combination

To define functions in Python, you can use positional arguments, default arguments, mutable arguments, named keyword arguments, and keyword arguments. Four of the five arguments can be used together, but note that the order in which the arguments are defined must be:

  • Positional parameters, default parameters, variable parameters, and keyword parameters.
  • Positional arguments, default arguments, named keyword arguments, and keyword arguments.

Note the syntax for defining mutable and keyword arguments:

  • * Args is a mutable parameter, and args receives a tuple
  • **kw is a keyword argument, and kw receives a dict

Keyword arguments are named to limit the parameter names that callers can pass in, and to provide default values. When defining named keyword arguments, don’t forget to write the * delimiter, otherwise you are defining positional arguments.

Caution: Although you can combine up to five parameters, do not use too many combinations at once or the function will become difficult to understand

The return value of the function

def add(a, b) :
    return a + b
print(add(1.2))  # 3
print(add([1.2.3], [4.5.6]))  # [1, 2, 3, 4, 5, 6]

In # 2
def back() :
    return [1.'A Little Pony's Programmed Life'.3.14]
print(back())  # [1, 'My Life ', 3.14]

# 3 cases
def back() :
    return 1.'A Little Pony's Programmed Life'.3.14
print(back())  # (1, 'My Little Pony ', 3.14)

# example 4
def printme(str) :
    print(str)
temp = printme('hello') # hello
print(temp) # None
print(type(temp))  # <class 'NoneType'>
Copy the code

Variable scope

  • In Python, program variables are not always accessible; access depends on where the variable is assigned.
  • A variable defined inside a function has a local scope and is called a local variable.
  • A variable defined outside a function has a global scope and is called a global variable.
  • Local variables can only be accessed inside the function they declare, whereas global variables can be accessed throughout the program
  • The global and nonlocal keywords are used when an inner scope wants to modify a variable in an outer scope
num = 1
def fun1() :
    global num  The global keyword is required
    print(num)  # 1
    num = 123
    print(num)  # 123
fun1()
print(num)  # 123
Copy the code

Inline function

def outer() :
    print('Outer is called from here.')
    def inner() :
        print('The inner function is called from here')
    inner()  This function can only be called from inside outer
outer()
# outer is called here
The # inner function is called here
Copy the code

closure

  • Is an important syntax structure of functional programming, is a special embedded function
  • An inner function is considered a closure if it refers to a variable in the outer layer that is not globally scoped
  • Closures provide access to variables that are outside the global scope, called the closure scope
def funX(x) :
    def funY(y) :
        return x * y

    return funY


i = funX(8)
print(type(i))  # <class 'function'>
print(i(5))  # 40
Copy the code
  • The nonlocal keyword is required if you want to modify a variable in the closure scope
def outer() :
    num = 10
    def inner() :
        nonlocal num  # nonlocal keyword declaration
        num = 100
        print(num)
    inner()
    print(num)
outer()

# 100
# 100
Copy the code

recursive

  • A function is recursive if it calls itself internally

Factorial n! = 1 x 2 x 3 x … x n

# Use the cycle
n = 5
for k in range(1.5):
    n = n * k
print(n)  # 120

# Use recursion
def factorial(n) :
    if n == 1:
        return 1
    return n * factorial(n - 1)
print(factorial(5)) # 120
Copy the code

Fibonacci numbers

# Use the cycle
i = 0
j = 1
lst = list([i, j])
for k in range(2.11):
    k = i + j
    lst.append(k)
    i = j
    j = k
print(lst)  
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

# Use recursion
def recur_fibo(n) :
    if n <= 1:
        return n
    return recur_fibo(n - 1) + recur_fibo(n - 2)
lst = list(a)for k in range(11):
    lst.append(recur_fibo(k))
print(lst)  
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Copy the code
  • Set the number of recursion levels. Python defaults to 100
import sys
sys.setrecursionlimit(1000)
Copy the code

Lambda expression –

Definition of anonymous functions

There are two types of functions in Python:

  1. A normal function defined with the def keyword
  2. Anonymous functions defined with lambda keywords

Python uses the lambda keyword to create anonymous functions instead of the def keyword, which has no function name and has the following syntax:

lambda argument_list: expression
Copy the code
  • Lambda – The keyword that defines an anonymous function.
  • Argument_list – Function arguments. These can be positional, default, or keyword arguments, the same types as arguments in regular functions.
  • A colon is added between function arguments and expressions.
  • Expression – Just an expression that takes in function arguments and outputs some values

Note:

  • There is no return statement in expression because lambda does not need it to return; the expression itself results in the return value.
  • Anonymous functions have their own namespace and cannot access arguments outside their own argument list or in the global namespace

The application of anonymous functions

Functional programming means that every piece of code is immutable and consists of pure functions. The pure function here means that the functions themselves are independent of each other and do not affect each other. For the same input, there will always be the same output without any side effects

# Nonfunctional programming
def f(x) :
    for i in range(0.len(x)):
        x[i] += 10
    return x
x = [1.2.3]
f(x)
print(x)
# [11, 12, 13]

# Functional programming
def f(x) :
    y = []
    for item in x:
        y.append(item + 10)
    return y
x = [1.2.3]
f(x)
print(x)
# [1, 2, 3]
Copy the code

Anonymous functions are often used in high-order functions of functional programming and have two main forms:

  1. Parameters are functions (filter, map)
  2. The return value is a function (closure)

For example, in the filter and map functions:

  • Filter (function, iterable) returns an iterator object that can be converted to a list using list()
odd = lambda x: x % 2= =1
templist = filter(odd, [1.2.3.4.5.6.7.8.9])
print(list(templist))  # [1, 3, 5, 7, 9]
Copy the code
  • Map (function, *iterables) maps the specified sequence based on the provided function
m1 = map(lambda x: x ** 2[1.2.3.4.5])
print(list(m1))  
# [1, 4, 9, 16, 25]
m2 = map(lambda x, y: x + y, [1.3.5.7.9], [2.4.6.8.10])
print(list(m2))  
# [3, 7, 11, 15, 19]
Copy the code
  • In addition to Python’s built-in functions, we can also define our own higher-order functions
def apply_to_list(fun, some_list) :
    return fun(some_list)

lst = [1.2.3.4.5]
print(apply_to_list(sum, lst))
# 15

print(apply_to_list(len, lst))
# 5

print(apply_to_list(lambda x: sum(x) / len(x), lst))
# 3.0
Copy the code

Classes and objects

Properties and methods make up objects

  • Object = property + method

An object is an instance of a class. In other words, a class defines the structure of an object, and then we create objects using the class as a template. A class contains not only method definitions, but also data shared by all instances.

  • Encapsulation: Information concealment technology

Python classes can be defined using the keyword class, which is followed by the class name, semicolon, and implementation of the class

  • Inheritance: A mechanism by which subclasses automatically share data and methods between their parents
  • Polymorphism: Different objects respond differently to the same method

What is self?

Python’s self is equivalent to the C++ this pointer

class Test:
    def prt(self) :
        print(self)
        print(self.__class__)


t = Test()
t.prt()
# <__main__.Test object at 0x000000BC5A351208>
# <class '__main__.Test'>
Copy the code

Methods of a class differ from ordinary functions only in one particular way — they must have an extra first argument name (corresponding to the instance, the object itself), which by convention is called self. We do not need to explicitly supply an argument corresponding to the argument self when calling the method

Python magic methods

  • The class has a name __init__(self[, param1, param2…] ), which is automatically called when the class is instantiated
class Ball:
    def __init__(self, name) :
        self.name = name

    def kick(self) :
        print("My name is % S, damn it, somebody kick me..." % self.name)

a = Ball("A")
b = Ball("B")
c = Ball("C")
a.kick()
# My name is Ball A, damn it, who kicked me...
b.kick()
# I call ball B, damn it, who kicked me...
Copy the code

Public and private

To define a private variable, you simply underline “__” before the name of the variable or function, and the function or variable is private

  • Class private property instance
class JustCounter:
    __secretCount = 0  # private variables
    publicCount = 0  # public variable

    def count(self) :
        self.__secretCount += 1
        self.publicCount += 1
        print(self.__secretCount)

counter = JustCounter()
counter.count()  # 1
counter.count()  # 2
print(counter.publicCount)  # 2

Python's private is pseudo-private
print(counter._JustCounter__secretCount)  # 2 
print(counter.__secretCount)  
# AttributeError: 'JustCounter' object has no attribute '__secretCount'
Copy the code
  • Class private method instance
class Site:
    def __init__(self, name, url) :
        self.name = name  # public
        self.__url = url  # private

    def who(self) :
        print('name : ', self.name)
        print('url : ', self.__url)

    def __foo(self) :  # private method
        print('This is a private method')

    def foo(self) :  # public method
        print('This is the public method.')
        self.__foo()


x = Site('The Old Horse of Procedural Life'.'https://blog.csdn.net/LSGO_MYP')
x.who()
# name: Lao Ma's App Life
# url : https://blog.csdn.net/LSGO_MYP

x.foo()
This is the public method
This is a private method

x.__foo()
# AttributeError: 'Site' object has no attribute '__foo'
Copy the code

inheritance

Definition of derived classes

class DerivedClassName(BaseClassName) :
       statement-1
              .
              .
              .
       statement-N
Copy the code

BaseClassName must be defined in the same scope as the derived class. In addition to classes, expressions can also be used, which is useful when the base class is defined in another module

class DerivedClassName(modname.BaseClassName) :
       statement-1
              .
              .
              .
       statement-N
Copy the code

Example: If a subclass defines a method or attribute with the same name as the parent class, the method or attribute corresponding to the parent class is automatically overwritten

# class definition
class people:
    # Define basic attributes
    name = ' '
    age = 0
    # define private attributes that cannot be accessed directly outside the class
    __weight = 0

    Define the constructor
    def __init__(self, n, a, w) :
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self) :
        print("% S said: I am % D." % (self.name, self.age))


# Single inheritance example
class student(people) :
    grade = ' '

    def __init__(self, n, a, w, g) :
        Call the parent constructor
        people.__init__(self, n, a, w)
        self.grade = g

    Override the superclass method
    def speak(self) :
        print("% S says: I am % D and I am in % D grade" % (self.name, self.age, self.grade))


s = student('A Little Pony's Programmed Life'.10.60.3)
s.speak()
I'm 10 years old and I'm in the third grade
Copy the code

__init__(self, n, a, w) : I am 0 years old and I am in grade 3 because the subclass constructor overrides the parent class constructor

Python supports a form of multiple inheritance, but we generally don’t use multiple inheritance because it can be confusing

combination

class Turtle:
    def __init__(self, x) :
        self.num = x


class Fish:
    def __init__(self, x) :
        self.num = x


class Pool:
    def __init__(self, x, y) :
        self.turtle = Turtle(x)
        self.fish = Fish(y)

    def print_num(self) :
        print("There are turtles %s and fish %s in the pool." % (self.turtle.num, self.fish.num))


p = Pool(2.3)
p.print_num()
There are two turtles and three small fish in the pool
Copy the code

Class, class object, and instance object

Class object: Creating a class, which is actually an object, also creates a space in memory called a class object. There is only one class object.

class A(object) :
       pass
Copy the code

Instance object: is created through the instantiation class object, called instance object, instance object can have more than one

  • Class attributes: Variables defined outside of methods in a class are called class attributes. A class attribute belongs to a class object and is shared by multiple instance objects. In other words, all objects instantiated by the class can be shared.
class A() :
    a = 0  # class attribute
    def __init__(self, xx) :
        A.a = xx  # Using class attributes can be done by (class name. Class property) call.
Copy the code
  • Instance attributes: Instance attributes are associated with an instance object, and one instance object does not share attributes with another. Instance attributes can only be used in its own object. Other objects cannot use instance attributes directly, because self is called by that object and its value belongs to that object
Create class object
class Test(object) :
    class_attr = 100  # class attribute

    def __init__(self) :
        self.sl_attr = 100  # instance attributes

    def func(self) :
        print('Class object. Values of class attributes :', Test.class_attr)  Call the class attribute
        print('self. value of class attribute ', self.class_attr)  This is equivalent to turning a class attribute into an instance attribute
        print('self. value of instance property ', self.sl_attr)  Call instance properties


a = Test()
a.func()

The value of the class attribute: 100
# self. The value of the class attribute is 100
The value of the instance attribute is 100

b = Test()
b.func()

The value of the class attribute: 100
# self. The value of the class attribute is 100
The value of the instance attribute is 100

a.class_attr = 200
a.sl_attr = 200
a.func()

The value of the class attribute: 100
# self. The value of the class attribute is 200
The value of the instance attribute is 200

b.func()

The value of the class attribute: 100
# self. The value of the class attribute is 100
The value of the instance attribute is 100

Test.class_attr = 300
a.func()

The value of the class attribute: 300
# self. The value of the class attribute is 200
The value of the instance attribute is 200

b.func()
The value of the class attribute: 300
# self. The value of the class attribute is 300
The value of the instance attribute is 100
Copy the code

The property is the same as the method name and overrides the method

What is binding?

Python’s strict requirement that methods have instances in order to be called is what Python calls a binding concept.

The data attributes of Python objects are usually stored in a dictionary named.__ dict__, which can be accessed directly from __dict__ or obtained using Python’s built-in vars()

Some related built-in functions (BIF)

  • The issubClass (class, classinfo) method is used to determine whether the class parameter is a subclass of the classinfo parameter.
  • A class is considered a subclass of itself.
  • Classinfo can be a tuple of class objects and returns True as long as class is a subclass of any of the candidate classes
  • The isinstance(object, classinfo) method is used to determine whether an object is of a known type, similar to type().
  • Type () does not consider a subclass to be a parent type, regardless of inheritance.
  • Isinstance () considers a subclass to be a superclass type, considering inheritance.
  • Always return False if the first argument is not an object.
  • If the second argument is not a class or a tuple of class objects, a TypeError exception is raised
  • Hasattr (Object, name) is used to determine whether an object contains corresponding attributes
  • Getattr (object, name[, default]) returns an object attribute value
  • Setattr (Object, Name, value) corresponds to the function getattr(), which is used to set the value of an attribute that may not exist
  • Delattr (object, name) is used to delete attributes
  • Class Property ([fget[, fset[, fdel[, doc]]]]) is used to return property values in modern classes.
    • Fget — The function that gets the value of an attribute
    • Fset – a function that sets the value of an attribute
    • Fdel — Removes attribute value functions
    • Doc — Attribute description information

Magic methods

Magic methods are always surrounded by double underscores, such as __init__.

Magic is everything in object-oriented Python, and if you don’t know magic, you haven’t realized how powerful object-oriented Python is.

The “magic” of magical methods is that they can always be invoked automatically at the right time.

The first argument to a magic method should be CLS (class method) or self (instance method).

  • CLS: Represents the name of a class
  • Self: Represents the name of an instance object

Basic magic methods

  • __init__(self[, …] Constructor, the initialization method called when an instance is created
  • __new__(cls[, …] The first method called when an object is instantiated calls __new__ before calling __init__ initialization.
    • New__ must have at least one argument, CLS, which represents the class to be instantiated. This argument is automatically provided by the Python interpreter at instantiation time, and subsequent arguments are passed directly to __init.
    • New__ instantiates the current class and returns the instance, passing it to self in __init__. However, __new does not necessarily enter __init__, only __new__ is returned, and only __init__ of the current CLS class is entered
    • If __new__ does not return an instance of the current CLS class correctly, __init__ will not be called, even if it is an instance of the parent class, __init__ will not be called
  • The __new__ method is mainly used when you inherit immutable classes (such as int, STR, or tuple) to give you a way to customize the instantiation of those classes
  • Del (self) destructor, a method called when an object is about to be reclaimed by the system
  • str(self):
    • When you print an object, trigger __str__
    • When you use %s formatting, trigger __str__
    • When STR forces a data type, __str__ is triggered
  • repr(self) :
    • The REPR is the spare tire of STR
    • __str__ is executed when __str__ is present, and __repr__ is executed when __str__ is not implemented
    • The result of the repr(obj) built-in function is the return value of __repr__
    • __repr__ is triggered when you use %r formatting

The return result of STR (self) is readable. In other words, the meaning of STR is to get information that is easy for people to read, just like ‘2019-10-11’ below.

The result returned by repr(self) should be more accurate. What is it to say that the repR exists for debugging purposes and is easy for developers to use

Arithmetic operator

Type factory functions, which means “create objects not from classes but from functions”

class C:
    pass


print(type(len))  # <class 'builtin_function_or_method'>
print(type(dir))  # <class 'builtin_function_or_method'>
print(type(int))  # <class 'type'>
print(type(list))  # <class 'type'>
print(type(tuple))  # <class 'type'>
print(type(C))  # <class 'type'>
print(int('123'))  # 123

The list factory function in this example processes a progenitor object into a list object.
print(list((1.2.3)))  # [1, 2, 3]
Copy the code
  • Add (self, other) defines the behavior of addition: +
  • Sub (self, other) defines the behavior of subtraction: –
  • Mul (self, other) defines the behavior of multiplication: *
  • Truediv (self, other) defines the behavior of true division: /
  • Floordiv (self, other) defines the behavior of integer division: //
  • Mod (self, other) defines the behavior of the mod algorithm: %
  • Divmod (self, other) defines the behavior when called by divmod()
  • Divmod (a, b) combines divisor and remainder and returns a tuple containing quotient and remainder (a // b, a % b)
  • Pow (self, other[, module]) defines the behavior when called or operated on by power()
  • Lshift (self, other) defines the bitwise left shift behavior: <<
  • Rshift (self, other) defines the bitwise right shift behavior: >>
  • And (self, other) defines the behavior of bitwise and operation: &
  • Xor (self, other) defines the behavior of bitwise xor operations: ^
  • Or (self, other) define the bitwise or operator behavior: |

The inverse arithmetic operator

Anti-operation rubik’s cube method, and arithmetic operators maintain a one-to-one correspondence, the difference is that the magic method of anti-operation more than an “R”. Called when the left operation of the file does not support the corresponding operation.

  • Radd (self, other) defines the behavior of addition: +
  • Rsub (self, other) defines the behavior of subtraction: –
  • Rmul (self, other) defines the behavior of multiplication: *
  • Rtruediv (self, other) defines the behavior of true division: /
  • Rfloordiv (self, other) defines the behavior of integer division: //
  • Rmod (self, other) defines the behavior of the modulo algorithm: %
  • Rdivmod (self, other) defines the behavior when called by divmod()
  • Rpow (self, other[, module]) defines the behavior when called or operated on by power()
  • Rlshift (self, other) defines the bitwise left shift behavior: <<
  • Rrshift (self, other) defines bitwise right shift behavior: >>
  • Rand (self, other) defines the behavior of bitwise and operation: &
  • Rxor (self, other) defines the behavior of bitwise xor operations: ^
  • Ror (self, other) define the bitwise or operator behavior: |

Incremental assignment

  • Iadd (self, other) defines the behavior of assignment addition: +=
  • Isub (self, other) defines the behavior of assignment subtraction: -=
  • Imul (self, other) defines the behavior of assignment multiplication: *=
  • Itruediv (self, other) defines the behavior of assigning true division: /=
  • Ifloordiv (self, other) defines the behavior of assigning integer division: //=
  • Imod (self, other) defines the behavior of the assignment modulus algorithm: %=
  • Ipow (self, other[, modulo]) defines the behavior of assigned powers: **=
  • Ilshift (self, other) defines the bitwise left shift behavior of assignment: <<=
  • Irshift (self, other) defines the bitwise right shift behavior of assignment: >>=
  • Iand (self, other) defines the behavior of assignment bitwise and operation: &=
  • Ixor (self, other) defines the bitwise xor operation of assignment: ^=
  • The ior (self, other) define the assignment the bitwise or operator behavior: | =

Unary operator

  • Neg (self) defines the behavior of the plus sign: +x
  • Pos (self) defines the behavior of the minus sign: -x
  • Abs (self) defines the behavior when called by abs()
  • Invert (self) defines the action of inverting bits: ~x

Property access

  • Getattr (self, name): Defines the behavior when a user tries to geta nonexistent attribute.
  • Getattribute (self, name) : Defines the behavior when an attribute of the class is accessed (call this method first to see if the attribute exists, and then call __getattr__ if it does not).
  • Setattr (self, name, value) : Defines the behavior when an attribute is set.
  • Delattr (self, name) : Defines the behavior when an attribute is deleted.

The descriptor

Descriptors are attributes that assign instances of a particular type of class to another class.

  • Get (self, instance, owner) is used to access the property, which returns the value of the property.
  • Set (self, instance, value) is called in the property assignment operation and returns nothing.
  • Del (self, instance) controls the deletion operation and does not return anything.

Custom sequence

Protocols are similar to interfaces in other programming languages in that they dictate which methods you must define. In Python, however, the protocol is less formal. In fact, in Python, protocols are more of a guide

Container type protocol

  • If you want custom containers to be immutable, you only need to define __len__() and __getitem__() methods.
  • In addition to the __len__() and __getitem__() methods, you also need to define __setitem__() and __delitem__() methods if you want your custom container to be mutable
  • Len (self) defines the behavior when called by len() (returns the number of elements in the container).
  • Getitem (self, key) defines the behavior of retrieving elements in the container, equivalent to self[key].
  • Setitem (self, key, value) sets the behavior of the specified element in the container, equivalent to self[key] = value.
  • Delitem (self, key) defines the action of deleting specified elements from the container, equivalent to del self[key]

The iterator

  • Iteration is one of Python’s most powerful features, as a way of accessing elements of a collection.
  • An iterator is an object that remembers the position of the iterator.
  • Iterator objects are accessed from the first element of the collection until all elements have been accessed.
  • Iterators can only move forward and not backward.
  • String, list, or tuple objects can all be used to create iterators
  • Iterators have two basic methods: iter() and next().
  • The iter(object) function is used to generate iterators.
  • Next (iterator[, default]) returns the next item of the iterator.
  • Iterator — iterable
  • Default — Optional, set to return the default value when there is no next element. If not set, the stopiterati-on exception will be raised if there is no next element
  • Iter (SE-LF) defines the behavior of elements in a container when iterating, returning a special iterator object that implements the next() method and identifies iteration completion with a StopIteration exception.
  • Next () returns the next iterator object.
  • The StopIteration exception is used to mark the completion of an iteration and prevent infinite loops. In the next() method, we can set the StopIteration exception to be raised to terminate the iteration after the specified number of loops are completed

The generator

  • In Python, functions that use yield are called generators.
  • Unlike normal functions, a generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator.
  • During a call generator run, each time yield is encountered, the function pauses and saves all current run information, returns the yield value, and continues from the current position on the next execution of the next() method.
  • Call a generator function that returns an iterator object