代码改变世界

python 装饰器

2017-12-21 10:36  龙武大帝  阅读(188)  评论(0编辑  收藏  举报
 1 user,passwd = "chuck","abc123"
 2 def outer(func):
 3     def inner(*args,**kwargs):
 4         print("please login first")
 5         login()
 6         ret = func(*args, **kwargs)
 7         return ret
 8     return inner
 9 
10 @outer    
11 def manager(x,y):
12     print("welcome manager page")
13     print(x,y)
14     return 'good boy'
15 
16 @outer
17 def home():
18     print("welcome your home")
19 
20 def login():
21     username = input("please input username:")
22     password = input("please input password:")
23     if username == user and password == passwd:
24         print("welcome come in")
25     else:
26         exit("Invalid username or passwd")
27 
28 abc = manager(1,2)
29 print(abc)
30 
31 home()
返回值

please login first
please input username:chuck
please input password:abc123
welcome come in
welcome manager page
1 2
good boy
please login first
please input username:chuck
please input password:abc123
welcome come in
welcome your home

@auth 相当于定义 manager=outter(manager)

然后我们调用manager(),然后outter(manager)的返回值是inner,那么现在执行manager() = inner(),但是我们在auth(func)的func里面传入的是manager,所以这个inner里面的func()又会回来执行manager(),这样就形成了一个完美的装饰器。

如果manager有返回值的话,我们可以使里面的inner函数返回一个值,这个值就是里面的func()函数的值,刚刚我们也说了,装饰器里面manager() = inner(),所以inner()的返回值也就相当于manager的返回值,自然传入的参数也是一样的。

 

user,passwd = "chuck","abc123"
def outer(auth_type):
    print("auth func", auth_type)
    def out_inner(func):
        def inner(*args,**kwargs):
            print("please login first")
            if auth_type == 'local':
                print("\033[31mI am %s\033[0m" % auth_type)
                login()
                ret = func(*args,**kwargs)
                return ret
            elif auth_type == 'ldap':
                print("\033[1;32mplease use %s\033[0m" % auth_type)
                func(*args,**kwargs)
        return inner
    return out_inner

@outer(auth_type="local")
def manager(x,y):
    print("welcome manager page")
    print(x,y)
    return 'good boy'

@outer(auth_type="ldap")
def home():
    print("welcome your home")

def login():
    username = input("please input username:")
    password = input("please input password:")
    if username == user and password == passwd:
        print("welcome come in")
    else:
        exit("Invalid username or passwd")


abc = manager(1,2)
print(abc)

home()
返回值

auth func local
auth func ldap
please login first
I am local
please input username:chuck
please input password:abc123
welcome come in
welcome manager page
1 2
good boy
please login first
please use ldap
welcome your home

 这里auth(auth_type="local")就是传入了auth_type参数,然后我们也可以在里面再加一层函数,方便传入外面的参数,这样的话就可以判断auth_type