zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    Ruby on rails开发从头来(windows)(二十七) 测试驱动开发
    数据库设计14技巧
    [原]DataReader 处理多个结果集—NextResult的用法
    MsSQL的字段类型
    在C#中把两个DataTable连接起来,相当于Sql的Inner Join方法
    征集佳句SQL导入导出大全
    [转贴]Hello NHibernate
    [转]数据库开发21条军规
    ASP.NET 中的正则表达式
    经典推荐—.NET相关最好东东(全球最新评价)
  • 原文地址:https://www.cnblogs.com/wangchaowei/p/9002734.html
Copyright © 2011-2022 走看看