python notes 17

1. Content Today

  • Iterator (3 *)
  • Generator (4 *)
  • Decorator (5 *)
  • Project structure
  • logging module

2. Recap & jobs

2.1 Recap

2.1.1 Function (Built / Custom)

  • The basic function structure

    def func(a1,a2):
        pass
    • parameter
    • return value
    • Perform functions
  • Small advanced functions

    • Function variables do
    • Function parameters do
  • Senior function

    • Do function return values
    • Nested functions
  • & Closure decorator

  • Recursion

  • Anonymous function

  • Built-in functions

2.1.2 module (internal / third party / Custom)

  • Definition module

    • Built-in: time / json / datetime / os / sys ... [re] module
    • Third Party:
      • installation:
        • pip package management tools: pip install xlrd
        • Source installation:
          • Download Source Package: compressed files.
          • unzip files
          • Open cmd window, and enter the directory: cd C: \ Python36 \ Lib \ site-packages
          • Execution: python36 setup.py build
          • Execution: python36 setup.py install
      • Installation Path: C: \ Python36 \ Lib \ site-packages
      • You know third-party modules:
        • Read xlrd, xlwd # excel in
        • requests
    • customize
      • py file
      • Folder __init__.py# py2 must have
  • Calling module

    • import

      • import function module 1. Module 1 ()
      • import module 1. Module 1 Module 2 Module 3 Module 2 Module 3 function ()
    • from xx import xxx

      • from module import function module function ()
      • from module import function module as ff ()
      • from module 1 function module import * () function 2 ()
      • from module import module module function ()
      • import module from the module as m m. function ()
    • Special case:

      • import folder loaded by default __init__.py
        call is --init--.py file content.

      • from file import *

        Files can be used directly in the function.

2.1.3 Other

  • Two value data exchange
  • Derivations
    • List (*)
    • dictionary
    • set

3. Content Today

Classes and Objects

3.1 iterator

I will not write iterators only.

Task: Please show all of the data list.

  • while + index + Counter

  • Iterators, for certain objects (str / list / tuple objects / dict / set class created) - iterable elements one by one in the acquisition, representation: a __next__method and each call can get the element iteration object ( after a front to obtain a).

    • List converted into iterator:

      • traveling v1 = ([11,22,33,44])
      • v1 = [11,22,33,44].__iter__()
    • Iterator want to get each value: Repeated calls val = v1.__next__()

      v1 = [11,22,33,44]
      
      # 列表转换成迭代器
      v2 = iter(v1)
      result1 = v2.__next__()
      print(result1)
      result2 = v2.__next__()
      print(result2)
      result3 = v2.__next__()
      print(result3)
      result4 = v2.__next__()
      print(result4)
      result5 = v2.__next__()
      print(result5)
      """
      # v1 = "alex"
      # v2 = iter(v1)
      # while True:
      #     try:
      #         val = v2.__next__()
      #         print(val)
      #     except Exception as e:
      #         break
    • To the last iteration, until the error: StopIteration error, it said that it has completed iterations.

    • How to determine whether an object is an iterator: whether there are internal __next__方法.

  • for loop

    v1 = [11,22,33,44]
    
    # 1.内部会将v1转换成迭代器
    # 2.内部反复执行 迭代器.__next__()
    # 3.取完不报错
    for item in v1:
        print(item)

3.2 iterables

  • Therein a __iter__()method and returns an iterator. (*)

    v1 = [11,22,33,44]
    result = v1.__iter__()
  • It may be for loop

3.3 generator (VARIOGRAM)

# 函数
def func():
    return 123
func()
# 生成器函数(内部是否包含yield)
def func():
    print('F1')
    yield 1
    print('F2')
    yield 2
    print('F3')
    yield 100
    print('F4')
# 函数内部代码不会执行,返回一个 生成器对象 。
v1 = func()
# 生成器是可以被for循环,一旦开始循环那么函数内部代码就会开始执行。
for item in v1:
    print(item)
def func():
    count = 1
    while True:
        yield count
        count += 1
        
val = func()

for item in val:
    print(item)

Summary: If there is a function in yield, then the function is a function generator, call the generator function returns a generator, the generator is only for the cycle, the internal generator function code that will execute each cycle will get yield value returned. You can not read loop used for yield (eg: yield before the return).

def func():
    count = 1
    while True:
        yield count
        count += 1
        if count == 100:#终止条件设置
            return

val = func()
for item in val:#item只取yield中的值。
    print(item)

Example: read file (the file to read page by page, 10 lines per page)

def func():
    """
    分批去读取文件中的内容,将文件的内容返回给调用者。
    :return:
    """
    cursor = 0
    while True:
        f = open('db', 'r', encoding='utf-8')# 通过网络连接上redis
        # 代指   redis[0:10]
        f.seek(cursor)
        data_list =[]
        for i in range(10):
            line = f.readline()
            if not line:
                return
            data_list.append(line)
        cursor = f.tell()
        f.close()  # 关闭与redis的连接


        for row in data_list:
            yield row


for item in func():
    print(item)
Other knowledge:
  • yeild from the keyword [less]
  • Less generator derivation []

to sum up

  • Iterator object of iterations may be performed by one element acquisition, internal iteration __next__ object has a method for obtaining the data to one.

  • Iterables such objects, and may be for loop in both methods __iter__ and to return an iterator (Builder).

  • Generator, the yield there is an internal function generator function, the function call returns a generator, the cycle generator, internal code will perform the function.

    Special iterator (**):

    def func():
        yield 1
        yield 2
        yield 3
    
    v = func()
    result = v.__next__()
    print(result)
    result = v.__next__()
    print(result)
    result = v.__next__()
    print(result)
    result = v.__next__()
    print(result)

    Special iterable:

    def func():
        yield 1
    
    v = func()
    result = v.__iter__()
    print(result)

Guess you like

Origin www.cnblogs.com/cuiyongchao007/p/12303316.html