Python 中的那些坑总结——持续更新
1.三元表达式之坑
很显然,Python把第一行的(10 + 4)看成了三元表达式的前部分,这个坑是看了《Python cookbook》(P5)中学到的,书中的代码:
2.Python生成器(yield)+递归
前两天一直纠结python的生成器递归该怎么写,今天看了os.walk()的代码恍然大悟,编程真是博大精深啊!不多说,上代码:
from os import path def walk(top, topdown=True, onerror=None, followlinks=False): islink, join, isdir = path.islink, path.join, path.isdir try: # Note that listdir and error are globals in this module due # to earlier import-*. names = listdir(top) except error, err: if onerror is not None: onerror(err) return dirs, nondirs = [], [] for name in names: if isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs for name in dirs: new_path = join(top, name) if followlinks or not islink(new_path): for x in walk(new_path, topdown, onerror, followlinks): # 生成器递归 yield x if not topdown: yield top, dirs, nondirs
3.try...finally + return:
如果写了try模块内有return且最后还有finally,那么会执行return后再执行finally。
这是从Queue的get方法里看到的,贴上自己写的测试代码:
附加Queue的get方法:
# Queue.py ...... def get(self, block=True, timeout=None): self.not_empty.acquire() try: if not block: if not self._qsize(): raise Empty elif timeout is None: while not self._qsize(): self.not_empty.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = _time() + timeout while not self._qsize(): remaining = endtime - _time() if remaining <= 0.0: raise Empty self.not_empty.wait(remaining) item = self._get() self.not_full.notify() return item finally: self.not_empty.release()
本人是软件工程专业的在校大学本科生,喜欢编程的小伙伴可以加我QQ一起探讨,QQ:312805939