From entry to prison-decorators, iterators/generators and modules

Getting started N day

  • Ginseng decorator

    When adding functions to a function, you can control specific operations through parameters (the operation is not fixed)

    '''
    格式:
    def 函数名0(装饰器的形参列表):
    	def 函数名1(func):
    		def 函数名2(*agrs,**kwargs):
    			result=func(*args,**kwargs)
    			添加的功能
    			return result
    		return 函数名2
    	return 函数名1
    有参装饰器的用法:
    @函数名0(装饰器实参列表)
    '''
    

    Write a decorator to print any specified prompt information after the function ends

    def end_message(x):
        def end(func):
            def new_func(*args,**kwargs):
                result = func(*args,**kwargs)
                print(x)
                return result
            return new_func
        return end
    @end_message('程序结束咯')
    def func1(x,y):
        print(x+y)
     
    func1(1,2)
    

    Exercise: Subtract the specified value from the return value of the original function

    def end_(x):
        def end(func):
            def new_func(*args,**kwargs):
                result=func(*args,**kwargs)
                if type(result) in (int, float, bool, complex):
                    return result-x
                return result
            return new_func
        return end
    @end_(15)
    def _():
        return 10
    print(_())
    
    
  • Iterator

    Iterator is a container data type (sequence)

    Features:

    Cannot view multiple elements at the same time (you can't see the elements when printing directly)

    Cannot count

    Can't view length

    When fetching elements, you can only fetch them one by one. Each time you fetch the top element, fetch one and one less

    —Create iterator —

    • Convert other sequences into iterators through iter

    • Create generator

    iter1=iter([10,20,30,40])
    print(iter1)   # # <list_iterator object at 0x000000000069CF88> 看不到里面的元素
    '''
    print(len(iter1))  #TypeError: object of type 'list_iterator' has no len() 不能统计个数(查看长度)
    
    '''
    

    Get the element from the iterator, the element does not exist in the iterator

    Only a single element can be taken at a time or converted to another sequence next (iterator) and traversal

    # 方法一  next
    iter1 = iter([10, 20, 30, 40])
    print(next(iter1))  # 10
    print(next(iter1))  # 20
    next(iter1)  # 取出来没有打印
    print(next(iter1))  # 40  这是最后一个元素,此时迭代器为空
    '''
    print(next(iter1)) # StopIteration  对空的迭代器取元素,会报错
    '''
    # 方法二 遍历
    iter2 = iter([10, 20, 30, 40])
    for i in iter2:
        print(i)  # 遍历iter2 依次将元素取出来直到迭代器为空
     
    '''
    iter3=iter('python!')
    list1=list(iter3)
    print(next(iter3)) # StopIteration
    报错的原因是因为迭代器iter3转换成为了列表
    那么原来iter3里面就没有元素了,所以再获取就会报错
    '''
    # 方法三 转换成列表
    iters = iter((10, 20, 30, 40))
    print(list(iters))  # [10, 20, 30, 40]
    
  • Builder

    The essence of the generator is an iterator, but the generator data source is different from the iterator

    If the iterator is seen as stacking eggs (data) one by one into the container

    Then the generator puts a hen (algorithm) and provides as many eggs (eggs) as needed

  • Create generator

    Call a function with the yield keyword to create a generator object

    If there is a yield in the called function, the function body will not be executed, and the function return value will not be obtained

    def func1():
        print('+++++')
        print('====')
        yield
        return 100
    result=func1()
    print(result)
    
  • How to determine the data generated in the generator

    The number of data generated: the function corresponding to the execution generator will encounter several yields

    The value of the generated data: see what the data behind the yield is encountered each time, if there is no data, it is None

    def func2():
        yield
        yield 'abc'
        for i in range(3):
            yield i
    
    
    gen1 = func2()
    print(gen1)
    list1 = list(gen1)
    print(list1, len(list1))  # [None, 'abc', 0, 1, 2] 5
    
    def func3(x):
        yield
        yield 'abc'
        if x & 1:
            yield 100
        return 20
        yield 10  # 遇不到
    
    
    print(list(func3(3)))
    # [None, 'abc', 100] 这里不会遇到20,因为前面有return函数体已经结束了
    
    
  • The principle of generator generating data

    The function body will not be executed when the function is called to create the generator object. It will be executed when the element in the generator is obtained. The first time the element is obtained, the execution will start from the beginning of the function body, and it will stop at the first yield. , And use the data after the yield as the element obtained this time. Each subsequent time the element is obtained, it is executed from the last end position and then executed. The next yield will stop after the execution. If you start from the current The position is executed to the end of the function and no yield is encountered, an error will be reported if it is acquired by next

    # 练习:写一个产生学号的生成器,能够产生指定学科001~999的学生学号
    
    def subject(subject):
        def create_num():
            for i in range(1, 1000):
                yield f'{subject}{i:0>3}'
    
        gen5 = create_num()
        for i in range(999):
            print(next(gen5))
    
    
    subject('java')
    # 写一个能够产生所有正偶数的
    def num():
        x = 0
        while True:
            x+=2
            yield x
    nums=num()
    print(next(nums))
    print(next(nums))
    print(next(nums))
    
  • Generative-the derivation of the generator

    Change the [] of the list comprehension into (), which is the deduction of the generator—the production formula

    list1=[i**2 for i in range(10)]
    print(list1)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    
    # 生成式
    gens=(i**2 for i in range(10))
    print(next(gens)) # 0
    print(next(gens)) # 1
    print(next(gens)) # 4
    

  • Module

A py file in python is a module, and the file name is the module name

You can use the content in another module in one module (functions, classes, and variables that are not in functions and classes), but you need to import the module in advance

If there is a module, it has the following code:

  print('.......')
  A = 100

  def func1():
      print('test1中的函数')

  for i in range(10):
      pass
  print('+++++++')
  • Import module

    Import the
    import module name in a project.
    After importing, you can use the global variables
    in the specified module . Use it in the form of'module name.variable'

    import test1
    print(test1.A)  #100
    test1.func1()
    print(test1.i)
    
    
    

    form module name import variable name 1, variable name 2...
    Import the module and use the specified global variable. The
    corresponding variable can be used directly without the need to use the "module name. variable" method

    from test1 import A,func1
    print(A)  # 100
    func1() #test1中的函数
    print(i)  # 会报错,因为没有导入i这个变量
    
    
  • Rename the module
    import module name as new module name Rename the
    module when importing the module.
    After renaming, you need to use the new module name to use the imported module

    import test1 as new_test1
    print(new_test1.A)  # 100
    new_test1.func1()  # test1中的函数
    print(new_test1.i) # 9
    
    
  • Rename the specified variable
    form module name import variable name 1 as new variable name, variable name 2, ...
    example

    from test1 import A as a,func1
    print(a)  # 100
    func1() #test1中的函数
    
    
  • Import all variables

    from module name import *

  • Principle of Import Module

    When importing a module, the system will automatically execute all the code in the imported module.
    Note: When
    importing a module, it has its own
    duplicate check function. If the imported module has already been imported, it will not be imported again.

    from test1 import A as a,func1   # .......  ++++++++
     '''
    
  • Prevent import if name ==' main ':

  • The variable used by the name system to save the module name

    print(__name__) # __main__
    

    Every time you run the current py file system name == main will execute the statement following
    if If you import the module, name ! = main will not execute the statement after the if,
    so the parts that do not need to be imported are placed after the if, which is to prevent the import

    def func1():
      pass
    
    def func2():
      pass
    def main():
      func1()
      func2()
    if __name__ == '__main__':
        main()
    

    Put global variables outside the if statement, and make function calls inside

    When others import a module, they will only execute the code outside the if, but not the code inside the if

Guess you like

Origin blog.csdn.net/weixin_44628421/article/details/109081448