偶尔需要复习一下装饰器的概念的什么的。可能需要看看这种小代码。
# -*- 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()