'''
一.python面试3大神器
1.装饰器
2.迭代器iterator
实现了__iter方法返回自身
实现了__next方法返回下一个元素,没有元素后抛StopIteration结束
3.生成器generator
语法糖的意思,使用了一个关键词叫yield, for loop循环里面所有的数字都是yield进去
generator的好处就是不用占用一整块的内存,把所有的数字都存储起来,你每次需要用的时候就调用一下next就会计算得到下一个值,你就可以用,然后比较省内存
区别就是一个是实现类方法__iter和__next方法
另一个就是一个方法return n 改为yield
二.3大引用
1.深浅拷贝赋值
2.对象引用
'''
class Counter:
def __init__(self, max):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n < self.max:
result = self.n
self.n += 1
return result
else:
raise StopIteration
counter = Counter(5)
for i in counter:
print(i)
def counter(max):
n = 0
while n < max:
yield n
n += 1
for i in counter(5):
print(i)
def aabb(n):
def outter(f):
def inner(*args, **kwargs):
print(n)
return f(*args,**kwargs)
return inner
return outter
@aabb(3)
def see_res(*args, **kwargs):
print(666)
see_res()
class ContextManager(object):
def __enter__(self):
print("[in __enter__] acquiring resources")
def __exit__(self, exception_type, exception_value, traceback):
print("[in __exit__] releasing resources")
if exception_type is None:
print("[in __exit__] Exited without exception")
else:
print("[in __exit__] Exited with exception: %s" % exception_value)
return False
with ContextManager():
print("[in with-body] Testing")
'''
引用计数,垃圾回收,内存池
1.手动垃圾回收
2.调高垃圾回收阈值
3.避免循环引用
'''