Python装饰器功能与使用误区示例
装饰器是Python中一种强大的特性,它允许我们在不修改已有代码的情况下,增加新的功能。
下面是一些关于装饰器的功能和使用误区的示例:
功能示例:
- 计时器:
@timeit
```python
import timeit
def my_function():
for i in range(1000):
pass
@timeit
my_function()
2. 日志记录:`@logger`
```python
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
def log_decorator(func):
def wrapper(*args, **kwargs):
logger.debug(f"Calling {func.__name__} with args {args}, kwargs {kwargs}")
return func(*args, **kwargs))
return wrapper
@log_decorator
def my_function():
print("Doing something")
my_function()
误区示例:
- 误认为装饰器就是修改函数行为:
@staticmethod
```python这样使用会报错,因为静态方法是类级别的方法,不是装饰器
class MyClass:
@staticmethod
def my_method():print("My method")
my_instance = MyClass()
my_instance.my_method() # 报错,因为这不是装饰器的用法
2. 误认为所有的函数都可以被装饰:`@non_function_decorator`
```python
def non_function_decorator(func):
return func
# 这样使用会报错,因为非函数(如类、属性等)无法直接装饰
class MyClass:
@non_function_decorator # 报错
def my_method(self):
print("My method")
my_instance = MyClass()
my_instance.my_method() # 报错
以上示例展示了Python装饰器的功能和使用误区。
还没有评论,来说两句吧...