1.闭包:
函数内部的子函数返回,在外部调用子函数时,其实函数已经结束,但是在调用子函数时,函数内部的局部变量任然有效。1 def fun(): 2 n = 10 3 def fun1(): 4 print('n为:', n) 5 return fun1 6 7 f = fun() 8 print(f) 9 f()10 11.fun1 at 0x000001DF0E6DFA60>12 n为: 10
--------------------------------------------------
2.装饰器:
参考:http://www.cnblogs.com/alex3714/articles/5765046.html软件开发的一个原则:开放-封闭 原则 开放:对现有功能的扩展开放 封闭:已实现的功能代码块不应该被修改------------------
# 对河南和欧美专区认证,若是已经登录过,就不需要在登录。
# 2.1.语法糖 装饰器
user_state = False
def login(func): def inner(): _username = 'alice' _password = '123' global user_state if user_state == False: username = input('username:').strip() password = input('password:').strip()if username == _username and password == _password:
print('welcome to login...') user_state = True else: print('wrong username or password') else: print('用户已经登录,认证通过') if user_state == True: func() return innerdef home():
print('-----首页-----')@login # america=login(america)def america(): print('-----欧美专区-----')def japan():
print('-----日韩专区-----')@login # henan=login(henan)def henan(): print('-----河南专区-----')home()
henan()america()-----首页-----
username:alicepassword:123welcome to login...-----河南专区-----用户已经登录,认证通过-----欧美专区-----语法糖 装饰器
# 2.2.带参数的装饰器
user_state = False
def login(func): def inner(*args, **kwargs): _username = 'alice' _password = '123' global user_state if user_state == False: username = input('username:').strip() password = input('password:').strip()if username == _username and password == _password:
print('welcome to login...') user_state = True else: print('wrong username or password') else: print('用户已经登录,认证通过') if user_state == True: func(*args, **kwargs) return innerdef home():
print('-----首页-----')@logindef america(): print('-----欧美专区-----')@logindef japan(x, y, z=5): print('-----日韩专区-----', x, y, z) @logindef henan(x): print('-----河南专区-----', x)home()
henan('haha')america()japan('japan', 1, z=7)-----首页-----
username:alicepassword:123welcome to login...-----河南专区----- haha用户已经登录,认证通过-----欧美专区-----用户已经登录,认证通过-----日韩专区----- japan 1 7带参数的装饰器
# 2.3.带参数2的装饰器
user_state = False
def login(auth_type): def outer(func): def inner(*args, **kwargs): _username = 'alice' _password = '123' global user_state if user_state == False: username = input('username:').strip() password = input('password:').strip()
if username == _username and password == _password:
print('welcome to login...') user_state = True else: print('wrong username or password') else: print('用户已经登录,认证通过') if user_state == True: func(*args, **kwargs) return inner return outerdef home():
print('-----首页-----')@login('wx')def america(): print('-----欧美专区-----')@login('wb')def japan(x, y, z=5): print('-----日韩专区-----', x, y, z)@login('qq') #henan = login('qq')(henan) =innerdef henan(x): print('-----河南专区-----', x)home()
# xx = login('qq')# henan = xx(henan)henan('haha')america()japan('japan', 1, z=7)-----首页-----
username:alicepassword:123welcome to login...-----河南专区----- haha用户已经登录,认证通过-----欧美专区-----用户已经登录,认证通过-----日韩专区----- japan 1 7带参数2的装饰器