Python基础(9)_生成器(yield表达式形式)、面向过程编程

时间:2023-03-09 04:05:20
Python基础(9)_生成器(yield表达式形式)、面向过程编程

一、yield表达式形式

 1 #装饰器,初始化含yield表达式的生成器
def init(func):
def wrapper(*args,**kwargs):
g=func(*args,**kwargs)
next(g)
return g
return wrapper
@init
def eater(name):
print('%s ready to eat'%name)
list=[]
while True:
food=yield list
list.append(food)
print('%s had eaten %s'%(name,food)) e=eater('alex')
print(e.send('鲍鱼'))
print(e.send('鱼翅'))

含yield表达式的生成器,在使用之前需要初始化,即执行一次net(g),将函数执行停留在yield处

send的效果:
   1:先从为暂停位置的那个yield传一个值,然后yield会把值赋值x
   2:与next的功能一样,如果yield后面有返回值,则返回该值,没有,返回值为None

二、os模块,递归取文件绝对路径

 import os
g=os.walk(r'D:\Pycharm Workspace') #g为生成器
for par_dir,_,files in g:
for file in files:
file_path=r'%s\%s'%(par_dir,file)
print(file_path)

三、面向过程编程

面向过程编程又叫函数式编程:

  函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计。函数就是面向过程的程序设计的基本单元。

核心:是过程,过程即流程

优点:思路清晰,复杂的问题简单化,流程化

缺点:扩展性差

应用:linux内核,httpd,git

 #模拟 grep ‘root’ /etc功能
import os
def init(func):
def wrapper(*args,**kwargs):
g=func(*args,**kwargs)
next(g)
return g
return wrapper
#阶段一:递归地找文件的绝对路径,把路径发给阶段二
@init
def search(target):
'search file abspath'
while True:
start_path=yield
g = os.walk(start_path)
for par_dir, _, files in g:
# print(par_dir,files)
for file in files:
file_path = r'%s\%s' % (par_dir, file)
target.send(file_path)
#阶段二:收到文件路径,打开文件获取获取对象,把文件对象发给阶段三
@init
def opener(target):
'get file obj: f=open(filepath)'
while True:
file_path=yield
with open(file_path,encoding='utf-8') as f:
target.send((file_path,f)) #阶段三:收到文件对象,for循环读取文件的每一行内容,把每一行内容发给阶段四
@init
def cat(target):
'read file'
while True:
filepath,f=yield
for line in f:
res=target.send((filepath,line))
if res:
break #阶段四:收到一行内容,判断root是否在这一行中,如果在,则把文件名发给阶段五
@init
def grep(target,pattern):
'grep function'
tag=False
while True:
filepath,line=yield tag #target.send((filepath,line))
tag=False
if pattern in line:
target.send(filepath)
tag=True
#阶段五:收到文件名,打印结果
@init
def printer():
'print function'
while True:
filename=yield
print(filename) start_path = r'D:\Pycharm Workspace\Day10'
g=search(opener(cat(grep(printer(),'root')))) print(g)
# g.send(start_path1)
g.send(start_path)

面向过程编程核心是过程,缺点是扩展性差

from峰哥:  

  函数的参数传入,是函数吃进去的食物,而函数return的返回值,是函数拉出来的结果,面向过程的思路就是,把程序的执行当做一串首尾相连的函数,一个函数吃,拉出的东西给另外一个函数吃,另外一个函数吃了再继续拉给下一个函数吃。。。

例如:
  用户登录流程:前端接收处理用户请求-》将用户信息传给逻辑层,逻辑词处理用户信息-》将用户信息写入数据库
  验证用户登录流程:数据库查询/处理用户信息-》交给逻辑层,逻辑层处理用户信息-》用户信息交给前端,前端显示用户信息