# Author Richard_Kong
# !/usr/bin/env python
# --*-- encoding:utf-8 --*--
"""
如果函数带有返回值,怎么办?
这就是更高级的装饰器:
1、带参数的装饰器:
@auth(auth_type="local")
此时它是一个函数,这种情况下 由于带有括号,会立即执行,但是只要它的返回值是一个装饰器就没问题
2、基于类的装饰器 和 带参数的类的装饰器
什么是装饰器呢:
装饰器:外部函数传入被装饰函数名,内部函数返回装饰函数名
特点:1、不修改被装饰函数的名称,2、不修改被装饰函数的源代码
home = timmer(home),等式右侧返回的是wrapper的内存地址,再将其赋值给home,这里的home不再是
原来的那个函数,而是被装饰以后的函数
像home = timmer(home)这样的写法,python给了我们特定的语法,@语法糖
如果一个函数被多个装饰器修饰。那它的执行顺序是由下到上
"""
def auth(auth_type):
print("auth_type:::",auth_type)
def outer_wrapper(func):
def wrapper(*args,**kwargs):
if auth_type=="local":
username = input("please input username:")
password = input("Please input password:")
if username == "richard_kong" and password == "abs123":
print("login successful")
func()
else:
exit("username or password is wrong!!")
elif auth_type =="lapd":
print("搞毛线lapd......不会!")
return wrapper
return outer_wrapper
@auth(auth_type="local")
def home(): # home = auth(home)
print("from home !!!")
def abs():
print("from abs!!!")
def login():
print("from abs!!!")
home()
python装饰器之中级篇
最新推荐文章于 2025-06-03 21:58:37 发布

本文深入探讨了Python中装饰器的概念及应用,包括无参与有参装饰器的实现方式,并通过具体实例展示了如何使用装饰器进行函数权限验证。
1万+

被折叠的 条评论
为什么被折叠?



