伪装者

# 装饰器
# x = 12
# def foo():
#     x = 123
#     print(x)
#     print("ok")
#
# print(foo.__name__)
# foo()
# LEGB 查找顺序

# x = 100
# def bar():
#     # x = 12
#     def inner():
#         # x = 0
#         print(x)
#     inner()
#
# bar()

# def foo():
#     print("foo")
#
# bar = foo
# bar()
# 闭包函数:内层函数应用了外层函数的的环境变量,这样的函数叫闭包函数

# def foo():
#     x =10
#     def inner():
#         y = 3
#         print(x)
#         print(y)
#     return inner
#
# func = foo()
# print(func.__closure__)
# x = 100
# func()

#################装饰器
#基于开放封闭原则
#1
# def index():
#
#     print("this is index!")
#
# index()
#2
# def index():
#
#     print("this is index!")
# def login():
#     user = input("user:>>>>>")
#     pwd = input("pwd:>>>>>")
#     if user == "alex" and pwd == "123":
#         print("success!")
#         index()
#     else:
#         print("error!")
# login()
##3
# def index():
# #
# #     print("this is index!")
# # def login(func):
# #     user = input("user:>>>>>")
# #     pwd = input("pwd:>>>>>")
# #     if user == "alex" and pwd == "123":
# #         print("success!")
# #         func()
# #     else:
# #         print("error!")
# # login(index)
##4

# def login(func):
#     def inner():
#         user = input("user:>>>>>")
#         pwd = input("pwd:>>>>>")
#         if user == "alex" and pwd == "123":
#             print("success!")
#             func()
#         else:
#             print("error!")
#     return inner
#
# @login
# def index():
#
#     print("this is index!")
# index()

#######练习

# def timer(func):
#     def inner():
#         import time
#         s1 = time.time()
#         func()
#         print("cost", time.time() - s1)
#     return inner
# @timer
# def add():
#     ret = 1
#     for i in range(30000000):
#         ret += i
#     print(ret)
#
# add()

def timer(func):
    def inner(x,y):
        import time
        s1 = time.time()
        func(x,y)
        print("cost",time.time()-s1)
    return inner

@timer
def add(x,y):
    print(x+y)

add(1,2)

 

posted @ 2018-11-08 18:51  被嫌弃的胖子  阅读(183)  评论(0编辑  收藏  举报