内容目录
迭代器生成器
装饰器
上下文管理器
迭代器
class Fib(object):
def __init__(self, num):
self.a, self.b = 0, 1
self.num = num
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > self.num:
raise StopIteration()
return self.a
fib = Fib(10)
for i in fib:
print(i) # 1 1 2 3 5 8
生成器
g = (x * x for x in range(5))
print(g) # <generator object <genexpr> at 0x0000025455677948>
for i in g:
print(i) # 0 1 4 9 16
def g(num):
for i in range(num):
yield i * i
for i in g(5):
print(i) # 0 1 4 9 16
装饰器
import functools
import time
#1 普通装饰器
def log(func):
@functools.wraps(func) # 把原始函数的__name__等属性复制到wrapper()函数中
def wrapper(*args, **kw):
print(func.__name__)
return func(*args, **kw)
return wrapper
@log
def func():
print('Hello')
func()
# func
# Hello
#2 传入参数的装饰器
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print(text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def func():
print('Hello')
func()
# execute func
# Hello
#3 装饰器类
class logit(object):
def __init__(self, msg):
self.msg = msg
print('init:', self.msg)
def __call__(self, func):
def wrapper(*args, **kw):
print(func.__name__)
print(self.msg)
return func(*args, **kw)
return wrapper
@logit('log')
def func():
print("Hello")
func()
# init: log
# func
# log
# Hello
上下文管理器
#1 基于类,定义enter和exit方法
class File(object):
def __init__(self, name, method):
self.file = open(name, method)
def __enter__(self):
return self.file
# exit返回True清空处理异常,否则抛出异常
def __exit__(self, type, val, trace):
self.file.close()
return True
with File('test.py', 'r') as f:
f.undefined_function()
print('Hello') # 这里不执行了
#2 基于生成器
from contextlib import contextmanager
@contextmanager
def open_file(name):
f = open(name, 'w')
yield f
f.close()
with open_file('test.txt') as f:
f.write('hello!')
扫码二维码 获取免费视频学习资料
- 本文固定链接: http://phpxs.com/post/11480/
- 转载请注明:转载必须在正文中标注并保留原文链接
- 扫码: 扫上方二维码获取免费视频资料
查 看2022高级编程视频教程免费获取