Python中幾個挺好用的東西(函數、類、裝飾器)

偶爾需要複習一下裝飾器的概念的什麼的。可能需要看看這種小代碼。

# -*- coding: cp936 -*-
#My_stuff

#C++ style output
import sys
class ostream(object):
    '''流對象,只能輸出'''
    def __init__(self,F):
        self.file = F
    def __lshift__(self,obj):
        self.file.write(str(obj));
        return self

class ofstream(ostream):
    '''文件流對象,只能輸出'''
    def __init__(self,FileName,flags = "w"):
        self.file = open(FileName,flags)
    def close(self):
        self.file.close()

cout = ostream(sys.stdout)
cerr = ostream(sys.stderr)
endl = '\n'

def timeit(func):
    '''測試時間用的裝飾器'''
    from time import clock
    # 定義一個內嵌的包裝函數,給傳入的函數加上計時功能的包裝
    def wrapper(*argv):
        start = clock()
        temp = func(*argv)
        cout << "argv=" << argv <<endl
        cout << 'time used:' << clock()-start << "s" << endl
        return temp
    # 將包裝後的函數返回
    return wrapper


def cached(f):
    """用來緩存的裝飾器"""
    f.cache = {}
    def replace(*argv):
        hs = hash(argv)
        if hs in f.cache:
            return f.cache[hs]
        else:
            temp = f(*argv)
            f.cache[hs]=temp
            return temp
    return replace

from pipe import *


class Pipe(object):
    """管道裝飾器,很難描述是用來做什麼的"""
    def __init__(self, function):
        self.function = function
       
    def __ror__(self, iterator):
        return self.function(iterator)
       
    def __call__(self, *args, **kwargs):
        return Pipe(lambda iterator: self.function(iterator, *args, **kwargs))

@Pipe
def print_each(x):
    """"經常要寫for i in x:print i,寫的次數實在太多了,我決定寫成一個可以放入管道的函數"""
    if type(x) in [ type([]) , type(())]:
        for i in x:
            print i
    elif type(x) == type({}):
        for i,j in x:
            print i,j
    else:
        print "Unknown type"
        exit()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章