一、叠加多个装饰器的加载、运行分析
def deco1(func1): #func1=wrapper2的内存地址
def wrapper1(*args,**kwargs):
print("正在运行deco1.wrapper1")
res1 = func1(*args,**kwargs)
return res1
return wrapper1
def deco2(func2): #func2=wrapper3的内存地址
def wrapper2(*args,**kwargs):
print("正在运行deco2.wrapper2")
res2 = func2(*args,**kwargs)
return res2
return wrapper2
def deco3(name): #func3=被装饰对象index的内存地址
def otter(func3):
def wrapper3(*args,**kwargs):
print("正在运行deco3.wrapper3")
res3 = func3(*args,**kwargs)
return res3
return wrapper3
return otter
#加载顺序自上而下
@deco1 #===> index =
deco1(wrapper2)的内存地址
@deco2 #====> index =
deco2(wrapper3)的内存地址
@deco3(111) #===> index =
wrapper3的内存地址
def index(x,y):
print("from index
%s:%s"%(x,y))
#执行顺序自上而下即
wrapper1>>>wrapper2>>>wrapper3
index(11,22)
二、yield返回值
def dog(name):
print(“道哥%s准备吃东西啦”%name)
while True:
#拿到的是yield接收到的值
X = yield #x=”肉包子”
print(“道哥%s吃了%s”%(name,x))
# g = dog(“alex”)
# g.send(None) #等同于next(g)
# g.send([“一根骨头“,”aaa”])
# g.close()
# g.send(“1111) #关闭之后无法传值
def dog(name):
food_list=[]
print(“道哥%s准备吃东西啦…”%name)
while True:
#x拿到的是yield接收到的值
X = yield food_list # x = “肉包子”
pint(“道哥%s吃了%s”%(name,x))
food_list.append(x) #[“一根骨头”,”肉包子”]
g = dog(“alex”)
res = g.send(None)
print(res)
res = g.send(“一根骨头”)
print(res)
def func():
print(“start….”)
x = yield 111
print(“aaaa”)
print(“aaaa”)
print(“aaaa”)
yield 222
g = func()
res = next(g)
print(res)
res = g.send(“xxxx”)
print(res)
三、三元表达式
语法格式:条什成立时要返回的值if 条件 else 条件不成立时要返回的值
X = 1
Y = 2
res = x if x > y else y
print(res)
#应用举例
def func():
#f 1 > 3:
# = 1
#lse:
# = 3
X = 1 if 1 >3 else 3
四、列表生成式
l = ['alex_dsb', 'lxx_dsb', 'wxx_dsb', "xxq_dsb", 'egon']
new_l = [name for name in l if name.endswith(“dsb”)]
new_l = [name for name in l]
print(new_l)
把所有小写字母全变成大写
nw_l = [name.upper() for name in l]
pint(new_l)
五、字典生成式
keys = [“name”,”age”,”gender”]
dic = {key:None for key in keys}
print(dic)
items=[(“name”,”egon”),(“age”,18),(“gender”,”male”)]
res = {k:v for k,v in items if k != “gender’}
print(res)
六、集合生成式
keys = [“name”,”age”,”gender”]
set1={key for key in keys}
print(set1,type(set1))
七、生成器表达式
With open(“a.txt”,mode=”rt”,encoding=”utf-8”) as f:
res = sum(len(line) for line in f)
print(res)
八、递归的定义
函数的递归调用:是函数嵌套调用的一种特殊形式
具体是指:在调用一个函数的过程中又直接或者间接地调用到本身
直接调用本身
def f1():
print(“是我还是我”)
f1()
f1()
间接调用本身
def f1():
print(“=èfi”)
f2()
def f2():
print(“=èf2”)
f1()
f1()
1、需要强调的一点是:递归调用不应该无限地调用下支,必须在满足某种条件下结束递归调用
2、递归的两个阶段
回溯:一层一层调用下支
递推:满足某种结束条件,结束递归调用,然后一层一层返回
# age(5) = age(4) + 10 # age(4) = age(3) + 10 # age(3) = age(2) + 10 # age(2) = age(1) + 10 # age(1) = 18 # def age(n): # if n == 1: # return 18 # return age(n-1) + 10 # # # res=age(5) # print(res)
3、递归的应用
l=[1,2,[3,[4,[5,[6,[7,[8,[9,10,11,[12,[13,]]]]]]]]]]
def f1(list1): for x in list1: if type(x) is list: # 如果是列表,应该再循环、再判断,即重新运行本身的代码 f1(x) else: print(x) f1(l)
来源:https://www.cnblogs.com/acnjanna2019/p/12566638.html