标签:__iter__ 外部 end global 红豆 取数 cep 公交 --
# 函数
# 修改全局变量
a = 10 def func(): global a a = 20 print(a) #10 func() print(a) #20 ----------------- # 外部访问局部变量
def outer(): a = 10 def func(): nonlocal a a = 20 return a def func(): b = outer() return b print(func()) #10
# 1 返回函数名 def outer(): def inner(): print("我是inner") return inner ret = outer() ret() # 2 闭包 里面用到了外面的变量 def func(): a = 10 def inner(): #定义inner print(a) inner() #调用inner print(inner.__closure__) # 能打印出东西就是闭包 func()
#装饰器
def wrapper(fn): def inner(*args,**kwargs): print(‘进站‘) ret = fn(*args,**kwargs) print(‘出检票‘) return inner @wrapper def train(): print(‘坐火车去拉萨‘) @wrapper def bus(): print(‘座公交车去拉萨‘) train() bus()
lst = ["张无忌", "胡辣汤", "赵敏", "灭绝"] # for循环的本质 it = lst.__iter__() # for循环的内部是用迭代器来获取数据的 while 1: try: item = it.__next__() print(item) except StopIteration: print("结束了") break
def order(): lst = [] for i in range(10000): lst.append("衣服%s" % i) return lst ret = order() print(ret[0]) # 下面生成器 工厂生产衣服的例子 def order(): for i in range(10000): yield "衣服%s" % i gen = order() print(next(gen)) print(gen.__next__())
# 生成器send 的传值的例子 def eat(): print("韭菜盒子") a = yield "红烧肉" print(a) b = yield "吱吱冒油的大肘子" print(b) # 绿豆汤 c = yield "地三鲜" print(c) # 红豆汤 g=eat() print("外面打印:" + g.__next__()) # yield "红烧肉" print("外面打印:" + g.send("疙瘩汤")) # yield "吱吱冒油的大肘子" print("外面打印:" + g.send("绿豆汤")) # yield "地三鲜" print("外面打印:" + g.send("红豆汤")) # 报错
def add(a, b): return a + b def gen_fun(): # 0 1 2 3 for i in range(4): yield i g = gen_fun() # 0 1 2 3 n=3 g = (add(i,5) for i in g) n=5 g = (add(i,5) for i in g) # # for n in [3, 5]: # g = (add(i, n) for i in g) print(list(g)) #[10, 11, 12, 13]
标签:__iter__ 外部 end global 红豆 取数 cep 公交 --
原文地址:https://www.cnblogs.com/zhangchen-sx/p/10952748.html