经过长时间学习Python装饰器,于是和大家分享一下,看完本文你肯定有不少收获,希望本文能教会你更多东西,学习Python装饰器时,你可能会遇到Python装饰器问题,这里将介绍Python装饰器问题的解决方法,在这里拿出来和大家分享一下。
***个函数deco是装饰函数,它的参数就是被装饰的函数对象。我们可以在deco函数内对传入的函数对象做一番“装饰”,然后返回这个对象(记住一定要返回 ,不然外面调用foo的地方将会无函数可用。
我写了个小例子,检查函数有没有说明文档:、static PyObject* thread_PyThread_start_new_thread(PyObject *self, PyObject
*fargs)
{
PyObject *func, *args, *keyw=NULL;
struct bootstate *boot;
long ident;
PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3, &func, &args, &keyw);
//[1]:创建bootstate结构
boot=PyMem_NEW(struct bootstate, 1);
boot->interp=PyThreadState_GET()->interp;
boot->funcfunc= func;
boot->argsargs= args;
boot->keywkeyw= keyw;
//[2]:初始化多线程环境
PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
//[3]:创建线程
ident=PyThread_start_new_thread(t_bootstrap, (void*) boot);
return PyInt_FromLong(ident);
[thread.c]
/* Support for runtime thread stack size tuning.
A value of 0 means using the platform's default stack size
or the size specified by the THREAD_STACK_SIZE macro. */
static size_t_pythread_stacksize=0;
[thread_nt.h]
long PyThread_start_new_thread(void (*func)(void *), void *arg)
{
Python装饰器是装饰函数,它的参数是用来加强“加强装饰”的。由于此函数并非被装饰的函数对象,所以在内部必须至少创建一个接受被装饰函数的函数,然后返回这个对象(实际上此时foo=decomaker(arg)(foo))。
这个我还真想不出什么好例子,还是见识少啊,只好借用同步锁的例子了:def synchronized(lock):
"""锁同步装饰方法
!lock必须实现了acquire和release方法
"""
def sync_with_lock(func):
def new_func(*args, **kwargs):
lock.acquire()
try:
return func(*args, **kwargs)
finally:
lock.release()
new_func.func_name= func.func_name
new_func.__doc__= func.__doc__
return new_func
return sync_with_lock
@synchronized(__locker)
def update(data):
"""更新计划任务"""
tasks=self.get_tasks()
delete_task=None
for task in tasks:
if task[PLANTASK.ID] == data[PLANTASK.ID]:
tasks.insert(tasks.index(task), data)
tasks.remove(task)
delete_task= task
r,msg=self._refresh(tasks, delete_task)
return r, msg, data[PLANTASK.ID]
调用时还是updae(data),同时还可以将多个装饰器组合 使用:def synchronized(lock):
"""锁同步装饰方法
!lock必须实现了acquire和release方法
"""
def sync_with_lock(func):
def new_func(*args, **kwargs):
lock.acquire()
try:
return func(*args, **kwargs)
finally:
lock.release()
new_func.func_name= func.func_name
new_func.__doc__= func.__doc__
return new_func
return sync_with_lock
@synchronized(__locker)
def update(data):
"""更新计划任务"""
tasks=self.get_tasks()
delete_task=None
for task in tasks:
if task[PLANTASK.ID] == data[PLANTASK.ID]:
tasks.insert(tasks.index(task), data)
tasks.remove(task)
delete_task= task
r,msg=self._refresh(tasks, delete_task)
return r, msg, data[PLANTASK.ID]
学后的总是感觉就是:Python装饰器可以让函数轻装上阵,更重要的是将函数的约束放置于接口处,使意图更加明了,同时又不增加调用者的负担,这贴子还是很肤浅的,我一定会回来的 !
【编辑推荐】
【责任编辑:苏越 TEL:(010)68476606】
点赞 0