标签:
s2.py
def outer(func): def inner(): print(‘log‘) return func() return inner @outer def f1(): print("F1") @outer def f2(): print("F2") @outer def f100(): print("F100")
b2.py
import s2 s2.f1() s2.f2() s2.f100() def f1(): print(123) def f1(): print(456) f1() # 输出结果: # 456 def f1(): print(‘123‘) def f2(xxx): xxx() f2(f1) # 输出结果: # 123
格式:@ + 函数名
功能:
1.自动执行outer函数,并且将其下面的函数名(f1)当作参数传递
2.将outer函数的返回值,重新赋值给其下面的函数的参数
s4.py
def outer(func): def inner(): print("before") func() print("after") return inner @outer def f1(): print("F1")
b2.py
import s4 s4.f1() 输出结果: before F1 after
s4.py
def outer(func): def inner(): print("before") r = func() print("after") return r return inner @outer def f1(): print("F1") return "kanni" b2.py import s4 ret = s4.f1() print("返回值", ret)
s4.py
def outer(func): def inner(a): print("before") r = func(a) print("after") return r return inner @outer def f1(arg): print(arg) return "kanni"
b2.py
import s4 ret = s4.f1(‘fafafa‘) print("返回值", ret)
s4.py
def outer(func): def inner(*args, **kwargs): print("before") r = func(*args, **kwargs) print("after") return r return inner @outer def f1(arg): print(arg) return "kanni" @outer def f2(a1, a2): print("F1")
b2.py
import s4 ret = s4.f1(‘fafafa‘) print("返回值", ret) s4.f2(11,22)
LOGIN_USER = {"is_login": False} def outer(func): def inner(*args, **kwargs): if LOGIN_USER[‘is_login‘]: r = func() return r else: print("请登录") return inner @outer def order(): print("欢迎%s登录" % LOGIN_USER[‘current_user‘]) @outer def changepwd(): print("欢迎%s登录" % LOGIN_USER[‘current_user‘]) @outer def manager(): print("欢迎%s登录" % LOGIN_USER[‘current_user‘]) def login(user, pwd): if user == "alex" and pwd == "123": LOGIN_USER[‘is_login‘] = True LOGIN_USER[‘current_user‘] = user manager() def main(): while True: inp = input("1.后台管理 2.登录") if inp == ‘1‘: manager() elif inp == ‘2‘: username = input("请输入用户名") pwd = input("请输入密码") login(username, pwd) main()
标签:
原文地址:http://www.cnblogs.com/liangdalong/p/5544015.html