Python语句、函数与方法的使用技巧总结
显示有限的接口到外部
当发布python第三方package时,并不希望代码中所有的函数或者class可以被外部import,在__init__.py中添加__all__属性,该list中填写可以import的类或者函数名, 可以起到限制的import的作用, 防止外部import其他函数或者类。
#!/usr/bin/env python # -*- coding: utf-8 -*- from base import APIBase from client import Client
from decorator import interface, export, stream from server import Server from storage import Storage
from util import (LogFormatter, disable_logging_to_stderr, enable_logging_to_kids, info)
__all__ = ['APIBase', 'Client', 'LogFormatter', 'Server',
'Storage', 'disable_logging_to_stderr', 'enable_logging_to_kids', 'export', 'info', 'interface', 'stream']
with的魔力
with语句需要支持上下文管理协议的对象, 上下文管理协议包含__enter__和__exit__两个方法。 with语句建立运行时上下文需要通过这两个方法执行进入和退出操作。
其中上下文表达式是跟在with之后的表达式, 该表达式返回一个上下文管理对象。
# 常见with使用场景
with open(\注意, 是__enter__()方法的返回值赋值给了my_file, for line in my_file: print line
知道具体原理,我们可以自定义支持上下文管理协议的类,类中实现__enter__和__exit__方法。
#!/usr/bin/env python # -*- coding: utf-8 -*- class MyWith(object): def __init__(self):
print \ def __enter__(self):
print \
return self # 返回对象给as后的变量
def __exit__(self, exc_type, exc_value, exc_traceback): print \ if exc_traceback is None:
print \ return True else:
print \ return False def test_with():
with MyWith() as my_with: print \ print \分割线-----\ with MyWith() as my_with: print \ raise Exception
print \if __name__ == '__main__': test_with() 执行结果如下:
__init__ method __enter__ method running my_with __exit__ method
Exited without Exception ------分割线----- __init__ method __enter__ method running before Exception __exit__ method Exited with Exception
Traceback (most recent call last): File \ exec(compile(__file__f.read(), __file__, \ File \ test_with()
File \ raise Exception Exception
证明了会先执行__enter__方法, 然后调用with内的逻辑, 最后执行__exit__做退出处理, 并且, 即使出现异常也能正常退出
filter的用法
相对filter而言, map和reduce使用的会更频繁一些, filter正如其名字, 按照某种规则过滤掉一些元素。
#!/usr/bin/env python # -*- coding: utf-8 -*- lst = [1, 2, 3, 4, 5, 6]
# 所有奇数都会返回True, 偶数会返回False被过滤掉 print filter(lambda x: x % 2 != 0, lst) #输出结果 [1, 3, 5] 一行作判断
当条件满足时, 返回的为等号后面的变量, 否则返回else后语句。
lst = [1, 2, 3]
new_lst = lst[0] if lst is not None else None print new_lst # 打印结果 1
装饰器之单例
使用装饰器实现简单的单例模式