如果你要写一个装饰器,推荐你一个url :http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 写的比较详细。
def deco(func):
def _deco(*args, **kwargs):
print("before %s called." % func.__name__)
ret = func(*args, **kwargs)
print(" after %s called. result: %s" % (func.__name__, ret))
return ret
return _deco
@deco
def myfunc(a, b):
print(" myfunc(%s,%s) called." % (a, b))
return a+b
@deco
def myfunc2(a, b, c):
print(" myfunc2(%s,%s,%s) called." % (a, b, c))
return a+b+c
这个时候a 2-item tuple of the list of positional arguments and a dictionary of keyword arguments ,就应该知道怎么传值了吧,举例一下:http://blog.csdn.net/chendejiao/article/details/43029461。
import threadpool as tp
def test(url, passwd):
print url, passwd
if __name__ == '__main__':
args = [
(['http://xxx.com', '123'], {}),
(['http://yyy.com', '213'], {}),
(['http://zzz.com', '321'], {})
]
pool = tp.ThreadPool(2)
reqs = tp.makeRequests(test, args)
[pool.putRequest(req) for req in reqs]
pool.wait()
以下是一个案例:
装饰器函数调用时间:
>>> import time
>>> class Timeit(object):
... def __init__(self, func):
... self._wrapped = func
... def __call__(self, *args, **kws):
... start_time = time.time()
... result = self._wrapped(*args, **kws)
... print("elapsed time is %s " % (time.time() - start_time))
... return result
...
...
>>> @Timeit
... def func():
... time.sleep(1)
... return "invoking function func"
...
>>> func()
elapsed time is 1.00166106224
'invoking function func'
类装饰器中报错
>>> class A(object):
... @Timeit
... def func(self):
... time.sleep(1)
... return 'invoking method func'
...
...
>>> A().func()
Traceback (most recent call last):
File "<input>", line 1, in <module>
A().func()
File "<input>", line 6, in __call__
result = self._wrapped(*args, **kws)
TypeError: func() takes exactly 1 argument (0 given)
实例并未传到__call__方法中去:
>>> class Timeit(object):
... def __init__(self, func):
... self.func = func
... def __call__(self, *args, **kwargs):
... start_time = time.time()
... result = self.func(*args, **kwargs)
... print("elapsed time is %s " % (time.time() - start_time))
... return result
... def __get__(self, instance, owner):
... return lambda *args, **kwargs: self.func(instance, *args, **kwargs)
...
...
...
>>> @Timeit
... def func():
... time.sleep(1)
... return "invoking function func"
...
>>>
>>> A().func()
'invoking method func'
我想__get__处理数据时间更快一些,怎么写呢?
>>> class Timeit(object):
... def __init__(self, func):
... self.func = func
... def __call__(self, *args, **kwargs):
... print('invoking Timer')
... def __get__(self, instance, owner):
... start_time = time.time()
... return_ = lambda *args, **kwargs: self.func(instance, *args, **kwargs)
... print("elapsed time is %s " % (time.time() - start_time))
... return return_
...
...
>>> class A(object):
... @Timeit
... def func(self):
... time.sleep(1)
... return 'invoking method func'
...
...
>>> A().func()
elapsed time is 1.90734863281e-06
'invoking method func'