def fibo(n): a,b=1,1 i = 3 while i <= n: if i == 1 or i == 2: return 1 else: a,b = b,a+b i += 1 else: print(b)
def gen(): print('a') count = yield 1 print ('--->',count) print ('b') yield 2 #注意打印结果 g = gen() next(g) g.send('123') next(g)
def save():
while True:
yield
print ('save')
def draw():
while True:
yield
print ('draw')
g1 = save()
g2 = draw()
while True:
next(g1)
next(g2)
def funcOut():
name = 'Jery'
def funcIn():
print(name)
return funcIn
f = funcOut()
f()
def funcOut():
name = 'abc'
def funcIn():
print(name)
pass
#如果打印None,则不是闭包函数
print(funcIn.__closure__)
return funcIn
f=funcOut()
f()
def outfunc(func): def infunc(): writeLog() func() return infunc def fun1(): print("使用功能1") def fun2(): print("使用功能2") # 注意名字的问题,需要分析 fun1 = outfunc(fun1) # 装饰器(闭包) fun1() 使用装饰器(语法糖)解决 def outfunc(func): def infunc(): writeLog() func() return infunc @outfunc def fun1(): print("使用功能1") @outfunc def fun2(): print("使用功能2") fun1() fun2()
def add1(fc):
print("add1正在装饰")
def wrapped():
return "《"+fc()+"》"
return wrapped
def add2(fc):
print("add2正在装饰")
def wrapped():
return '*'+fc()+'*'
return wrapped
#看到这个,开始进行装饰,而不是等到调用时
@add1
@add2
def test1():
return '金陵十三钗'
print(test1())
def func(fn):
print("func")
def func_in(aa, bb):
print("func_in1")
fn(aa,bb)
print("func_in2")
return func_in
@func
def test(a, b):
print("a=%d,b=%d" % (a, b))
# 装饰器装饰之后,这不是直接调用test方法,而是调用func_in方法
test(1,2)
def func(fn):
# 需要有参数,*args,**kwargs
def func_in(*args,**kwargs):
print("记录日志")
print('访问方法:'+fn.__name__)
# 需要有参数,*args,**kwargs
xx = fn(*args,**kwargs)
# 需要有返回值
return xx
return func_in
# 待装饰函数:无参数,无返回值
@func
def test1():
print("test1")
test1()
@func
def test2():
return "Hello"
print(test2())
@func
def test3(a):
print('a=%d'%a)
test3(1)
class Goods(): discount = 1 def __init__(self,price,name): self.name = name self.price = price def price_discount(self): return self.price * Goods.discount @classmethod def change_discount(cls,new_discount): cls.discount = new_discount