优美的python
举几个鲜为人知的例子,却很能提升代码品味。
使用next获取循环中符合条件的值
#bad
a = -1
for i in range(1,10):
if not i%4:
a = i
break
#good
a = next((i for i in range(1,10) if not i % 4), -1)
#比较好的缓存写法
import urllib
from functools import wraps
def cache(func):
saved = {}
@wraps(func)
def deco(*args, **kwargs):
if not saved[args]: saved[args] = func(*args, **kwargs)
return saved[args]
return deco
@cache
def web_lookup(url):
return urllib.request.urlopen(url).read()
执行调用直到某种情况结束
#bad
res = ""
with open("./help.txt", "r") as f:
while True:
buff = f.read(32)
if buff == "": break
res += buff
print(res)
#good
import os
from functools import partial
here = os.path.dirname(__file__)
res = ""
with open(os.path.join(here, "help.txt"), "r") as f:
for buff in iter(partial(f.read, 32), ""):
res += buff
print(res)
#bad
def find(seq, target):
found = False
for i, value in enumerate(seq):
if value == target:
found = True
break
return found
#good
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
# found = True
break
else:
return -1
return i
#第二种方法不用引入found变量
partialmethod的用法
from functools import partialmethod
#实例一
def get_name(self):
return self._name
class Cell(object):
def __init__(self):
self._alive = False
self._name = self.__class__
@property
def status(self):
return self._alive
def set_state(self, state):
self._alive = bool(state)
#partialmethod就是作用于类方法的partial
set_alive = partialmethod(set_state, True)
set_dead = partialmethod(set_state, False)
get_name = partialmethod(get_name)
cell = Cell()
print(cell.status)
cell.set_alive()
print(cell.status)
cell.set_dead()
print(cell.status)
print(cell.get_name())#可以直接调用类外部的类方法
#事例二
class Request(object):
default_url = "www.baidu.com"
def request(self, method, url, params=None, data=None):
print("execute request {} method {}".format(url, method))
# return self.METHOD_MAP.get(method)
get = partialmethod(request,"GET")
post = partialmethod(request,"POST")
put = partialmethod(request,"PUT")
delete = partialmethod(request,"DELETE")
get_default_url = partialmethod(get, default_url)
r = Request()
r.get_default_url()
r.get("shen.com")
r.put("xian.com")