生成器:
1、函数
def A(): for i in range(10): yield i → ##将函数变成一个迭代器(生成器) a=A() print(next(a)) print(next(a)) 输出:0 1
2、try、except;
尝试执行try中的代码,如果有错,则被except捕获,但是整个程序不会崩溃,
def A(): for i in range(5): yield i ##将函数变成一个迭代器(生成器) try: a=A() print(next()) print(next()) print(next()) print(next()) print(next()) print(next()) except Exception as e: print(e) print('Hello world')
输出:0
1
2
3
4
Hello world
装饰器:
def deco(func): def warp(name1): print('warp') name1 = 10000 return func(name1) return warp @deco def jy(name): print(name) jy('zxy')
输出:warp
10000
1、不定长参数
1.1 *args 位置传参
def haha(*args): print(args) haha(1,2,3,4)
输出:(1,2,3,4) → 元组
1.2 **kwargs带参数名称传参
def lala(**kwargs): print(kwargs) lala(a=1,b=2,c=3)
输出:{'a': 1, 'b': 2, 'c': 3} → 字典
↓ ↓
键名 键值
1.3 *args 和 **kwargs 混合掺活
## *args 一定要放前面
def heihei(*args,**kwargs): print(args) print(kwargs) heihei(1,2,3,a=1,b=2,c=3)
输出:(1, 2, 3)
{'a': 1, 'b': 2, 'c': 3}
2、装饰器代参
def deco2(param): print(param) def deco(func): def warp(*args,**kwargs): print(args) print(kwargs) kwargs['name2']=10000 return func(*args,**kwargs) return warp return deco @deco2(100) def lele(name2): print(name2) lele(name2='jy