装饰器和迭代器
迭代器
1.for 表达式
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [(x,x-1) for x in range(10) if x%2==0]
[(0, -1), (2, 1), (4, 3), (6, 5), (8, 7)]
[(x,y,z) for x in range(5) for y in range(10,20,2) for z in range(5)]
[x for x in dir(os) if not x.startswith('__')]
2.生成器
生成器写法一:
(x for x in range(10))
((x,x-1) for x in range(10) if x%2==0)
((x,y,z) for x in range(10) for y in range(10,20,2) for z in range(10))
生成器写法二:
def f():
yield
调用方式:
f.__next__()
next(a)
for循环
send()
3.迭代器 iterator
拥有__next__() 方法和__iter__() 方法的对象
装饰器
# 导入 logging 包
import logging
def decorator(func):
def wrapper(*args, **kwargs):
try:
# Call the original function
result = func(*args, **kwargs)
# Log successful execution
logging.info(f"Function {func.__name__} called with args: {args}, kwargs: {kwargs}")
return result
except Exception as e:
# Log error with exception details
logging.error(f"Error in {func.__name__}: {str(e)}", exc_info=True)
# Re-raise the exception
raise
return wrapper
@decorator
def test(name):
# Intentionally raise a ZeroDivisionError
print(1/0)
# Configure logging (you may want to adjust the level and format)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Call the test function
test('zhangsan')
class Persion(object):
def __init__(self, name):
self.name=name
def aa(fn):
def new(*args,**kwargs):
print('这一行用于判断')
fn(*args,**kwargs)
print('这一行是日志')
return new
@aa
def say(self,address):
print(self.name,address)
# p=Persion('wangendao')
# p.say('sz')
class BlackPersion(Persion):
def __init__(self, name):
super().__init__(name)
@Persion.aa
def new(self):
print(self.name)
b=BlackPersion('zhansan')
b.say('fz')
b.new()