Python Day 4 装饰器

装饰器:本质是函数,(装饰其他函数),也叫语法糖
就是为其他函数添加附加功能
原则:
1. 不能修改被装饰函数的源代码
2. 不能修改被装饰函数的调用方式
3. 但是会改变返回值

实现装饰器知识储备:
1. 函数即“变量”
2. 高阶函数
a:把一个函数当做实参传给另外一个函数
(不修改被装饰函数源代码的情况下,为其添加功能)
b:返回值中包含函数名

装饰器语法

@timer #test1=timer(test1)
def test1():
    time.sleep(3)
    print("in the test1")
@timer
def test2(name,age):
    time.sleep(3)
    print("in the test2",name,age)
test1()
test2("Eric",21)
user_status=False
def login(func):
    def inner(*args,**kargs):
        _username="alex"
        _password="abc123"
        global user_status

        if user_status==False:
            username=input("u:")
            password=input("p:")

            if username==_username and password==_password:
                print("welcome login!")
                user_status=True
            else:
                print("wrong password")
    return inner

@login
def home(style):
    print("-------home-------")

home("home?")
posted @ 2017-07-19 10:56  AbyssCE  阅读(81)  评论(0编辑  收藏  举报