如何写出 Pythnnic 的工程代码:
命令行工具和正则是最基本的工具
写出一个只有一个文件的 Pythonic 代码并不难,写出一堆代码只为完成任务也不难,难的就在于 如何非常优雅地实现一个整个 Pythonic 的工程代码。
下面是一个常有的 utils:
#!/usr/bin/env python | |
import multiprocessing | |
import os | |
import requests | |
######################################################################## | |
class MultiProcDownloader(object): | |
""" | |
Downloads urls with Python's multiprocessing module |
# -*- coding:utf-8 -*- | |
""" | |
configcc.py 是配置文件,内容为:index=42 | |
""" | |
import time | |
from functools import wraps | |
import hashlib | |
import configcc |
def test(): | |
num = 2366 | |
first, _second_ = divmod(num, 1000) # first is 2 | |
third, _fourth_ = divmod(_second, 100) # third is 3 | |
fifth, sixth = divmod(_fourth, 10) # fifth is 6,fourth is 6 | |
# return ''.join("第",...etc) bother troubling shoot ^-^ | |
return "第" + _converter(first) + "千" + _converter(third) + "百" \ | |
+ _converter(fifth) + "十" + _converter(sixth) | |
Mozilla/5.0 (compatible; U; ABrowse 0.6; Syllable) AppleWebKit/420+ (KHTML, like Gecko) | |
Mozilla/5.0 (compatible; U; ABrowse 0.6; Syllable) AppleWebKit/420+ (KHTML, like Gecko) | |
Mozilla/5.0 (compatible; ABrowse 0.4; Syllable) | |
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Acoo Browser 1.98.744; .NET CLR 3.5.30729) | |
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Acoo Browser 1.98.744; .NET CLR 3.5.30729) | |
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Acoo Browser; GTB5; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; InfoPath.1; .NET CLR 3.5.30729; .NET CLR 3.0.30618) | |
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; Acoo Browser; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Avant Browser) | |
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506) | |
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; GTB5; Mozilla/4.0 (comp |
/* Exercise: Loops and Functions #43 */ | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func Sqrt(x float64) float64 { | |
z := float64(2.) |
如何写出 Pythnnic 的工程代码:
命令行工具和正则是最基本的工具
写出一个只有一个文件的 Pythonic 代码并不难,写出一堆代码只为完成任务也不难,难的就在于 如何非常优雅地实现一个整个 Pythonic 的工程代码。
下面是一个常有的 utils:
附录1:
call 的使用:
可以帮忙创建良好的 API,举几个例子:
① Django 实现的 Validators
② june 里实现的 用户验资
# -*- coding:utf-8 -*- | |
import re | |
RE_WORD=re.compile(r'\w+') | |
class Sentence(object): | |
def __init__(self,text): | |
self.text=text | |
self.words=RE_WORD.findall(text) |
Part I
实现了 getitem 后就可以用 c[0] 这种 和 c[:2] 切片模式
在调用 in 这个方法时,如果没有 contains 方法,但它是 iterable 可迭代的,那么这也会起作用
class Vector:
def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
str2int=lambda s:sum(int(v)*10**i for i,v in enumerate(s[::-1])) | |
str2int=lambda s:reduce((lambda x,y:x*10+y),map(int,s)) |