掌握Python装饰器函数的10个实例
Python中的装饰器函数是一个很有用的特性,它可以在函数的前面添加某些装饰语句或操作,这样可以方便地进行代码扩展或修改。在学习Python装饰器函数之前,我们需要先了解什么是高阶函数。
高阶函数是Python中一种特殊的函数类型,能够使用其他函数作为参数或返回其他函数。在Python中,我们可以将这种函数传递给其他函数,或者在其他函数中使用这种函数来在运行过程中动态进行代码扩展或修改。
下面是使用Python装饰器函数的10个实例。
1. 装饰函数
使用装饰器函数可以方便地对函数进行修改,例如为函数添加一些操作或输出结果。
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello World")
say_hello()
输出结果:
Before function call Hello World After function call
2. 装饰类方法
与装饰函数类似,可以使用装饰器函数对类方法进行修改或添加一些操作。
def my_decorator(func):
def wrapper(self):
print("Before function call")
func(self)
print("After function call")
return wrapper
class MyClass:
@my_decorator
def say_hello(self):
print("Hello World")
obj = MyClass()
obj.say_hello()
输出结果:
Before function call Hello World After function call
3. 计时器装饰器
使用计时器装饰器可以方便地计算函数运行的时间。
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function took {end_time - start_time:.2f}s to run.")
return result
return wrapper
@timer
def my_func():
time.sleep(2)
my_func()
输出结果:
Function took 2.00s to run.
4. 日志装饰器
使用日志装饰器可以方便地记录函数的执行情况,以便于调试和错误处理。
def logger(func):
import logging
logging.basicConfig(filename='{}.log'.format(func.__name__), level=logging.INFO)
def wrapper(*args, **kwargs):
logging.info('Function {} called with args={}, kwargs={}'.format(func.__name__, args, kwargs))
return func(*args, **kwargs)
return wrapper
@logger
def my_func(*args, **kwargs):
pass
my_func(1, 2, 3, name="John")
输出结果:
INFO:root:Function my_func called with args=(1, 2, 3), kwargs={'name': 'John'}
5. 缓存装饰器
使用缓存装饰器可以缓存函数的结果以提高函数的性能。
def memoize(func):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
@memoize
def fibonacci(n):
if n in (0, 1):
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))
输出结果:
55
6. 认证装饰器
使用认证装饰器可以方便地进行用户身份验证,以保护某些敏感的操作或资源。
def authenticate(func):
def wrapper(*args, **kwargs):
username = input("Username: ")
password = input("Password: ")
if username == "admin" and password == "secret":
return func(*args, **kwargs)
else:
raise Exception("Authentication failed!")
return wrapper
@authenticate
def my_func():
print("Access granted")
my_func()
输出结果:
Username: admin Password: secret Access granted
7. 条件装饰器
使用条件装饰器可以方便地根据某些条件来决定是否执行函数或是否使用装饰器。
def conditional_decorator(condition, decorator):
def wrapper(func):
if not condition:
return func
return decorator(func)
return wrapper
@conditional_decorator(True, memoize)
def fibonacci(n):
if n in (0, 1):
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))
输出结果:
55
8. 被装饰函数带参数的装饰器
使用被装饰函数带参数的装饰器可以方便地对带参数的函数进行装饰。
def my_decorator(arg):
def wrapper(func):
def inner_wrapper(*args, **kwargs):
print(f"Before function call with arg={arg}")
result = func(*args, **kwargs)
print(f"After function call with arg={arg}")
return result
return inner_wrapper
return wrapper
@my_decorator("hello")
def my_func():
print("world")
my_func()
输出结果:
Before function call with arg=hello world After function call with arg=hello
9. 组合装饰器
使用组合装饰器可以方便地将多个装饰器进行组合使用,以完成复杂的操作或扩展。
def makeitalic(func):
def wrapper(*args, **kwargs):
return "<i>" + func(*args, **kwargs) + "</i>"
return wrapper
def makelabel(title):
def decorator(func):
def wrapper(*args, **kwargs):
return "<label>" + title + "</label>" + func(*args, **kwargs)
return wrapper
return decorator
@makeitalic
@makelabel("My Title")
def say_hello():
return "Hello World"
print(say_hello())
输出结果:
<label>My Title</label><i>Hello World</i>
10. 类装饰器
使用类装饰器可以方便地对类的属性和方法进行修改或扩展。
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("Before function call")
self.func(*args, **kwargs)
print("After function call")
@MyDecorator
def say_hello():
print("Hello World")
say_hello()
输出结果:
Before function call Hello World After function call
总结:
Python装饰器函数是Python中一个非常重要的特性,可以方便地对函数进行修改或扩展,以完成更复杂的操作或任务。在实际开发中,我们可以使用各种类型的装饰器函数来加速开发过程,提高代码的可扩展性和重用性。
