Python中几个挺好用的东西(函数、类、装饰器)
2012-08-31 19:31
357 查看
偶尔需要复习一下装饰器的概念的什么的。可能需要看看这种小代码。
# -*- 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()
相关文章推荐
- Python生成随机数与random模块中最常用的几个函数
- python 实现 Peceptron Learning Algorithm ( 一) 几个函数的记录
- python-Levenshtein几个计算字串相似度的函数解析
- Python 几个内建函数: map, reduce,filter,sorted 整理
- python中几个内建函数
- Python函数传参的几个注意点
- python装饰器的4中类型:函数装饰函数、函数装饰类、类装饰函数、类装饰类
- python函数递归的几个例子
- python 实现 Peceptron Learning Algorithm ( 一) 几个函数的记录
- python的几个内建函数:apply(),filter(),map(),reduce()
- python基础—(高阶,匿名,偏)函数 | 装饰器
- 小白学Python(三) 几个简单的函数
- python几个重要的函数(lambda,filter,reduce,map,zip)
- Python Day4 函数 装饰器
- python使用装饰器和线程限制函数执行时间的方法
- python中关于小数点后面的数四舍五入问题解决的几个函数供大家参考,现在问题是如何动态输入小数点后多少位,比如12.3000这样的
- python几个排序函数 sort sorted argsort
- python-Levenshtein几个计算字串相似度的函数解析
- python的几个内建函数:apply(),filter(),map(),reduce(
- 装饰器应用,Python模块学习之(__call__)实现准确计算函数运行时间