A sentence A picture A day!

Python 味道[1]

先用pyhton写一段快排:

def quicksort(array):
    if len(array)<=1:
        return array
    less = [];
    greater = [];
    base = array.pop()
    for i in array:
        if i>=base:
            greater.append(i)
        else:
            less.append(i)
    return quicksort(less)+[base]+quicksort(greater)

python味道: 像伪代码像写文章;代码风格整齐;理解它的标准库;库和框架,强调团队

编写函数4原则:

  • 函数尽量短小,嵌套层次不要过深
  • 函数声明简单、易于使用。名字合理,参数不要过多
  • 函数参数设计考虑向下兼容。通过加入默认参数避免退化,做到向下版本更新兼容 def play(name,type=a.info):
  • 一个函数只做一件事,语句粒度一致性【高级抽象与细粒度的字符处理】

将常量集中到一个文件中:

在python中使用常量:

  • 命名风格,常量名全部大写
  • 自定义类实现常量功能。要符合“命名全部为大写”和“值一旦绑定不可再修改”,解决方法见下,通过命名不符合规则时和修改时抛出异常解决。

    class _const: #私有类
        class ConstError(TypeError):pass
        class ConstCaseError(ConstError):pass
    
        def _setattr__(self,name,value):#__xxx__ 系统定义名字
            if self.__dict__.has_key(name):
                raise self.ConstError,"Cannot change%s" % name
            if not name.upper():
                raise self.ConstCaseError,'const "%s" is not all uppercase' % name
    
            self.__dict__[name]=value
    
    import sys
    sys.modules[__name__]=_const()
    

上述模块命名为const.py,使用方式如下

    import const
    const.MY_CONSTANT = 1
    const.MY_SECOND_CONSTANT = 'a'

在其他模块中引用这些常量【将上面的文件命名为constant.py】

from constant import const
print const.MY_SECOND_CONSTANT