程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Some tips on Python decorators

編輯:Python

Timing of invocation

The decorator is called at the time of import , Or execute when loading , The following code :

register = []
def regester(func):
print 'running regisster ({0})'.format(func)
register.append(func)
return func
@regester
def f1():
print "running f1()"
@regester
def f2():
print "running f2()"
def f3():
print "running f3()"
def main():
print "running main()"
print register
f1()
f2()
f3()

The results are as follows :

running regisster (<function f1 at 0x1035ae5f0>)
running regisster (<function f2 at 0x1035ae668>)
running main()
[<function f1 at 0x1035ae5f0>, <function f2 at 0x1035ae668>]
running f1()
running f2()
running f3()

Follow the normal code execution logic to execute , So the first print out should be "running main()", But it actually came out on the third line , The first two lines are the contents of the decorator , use Debug Mode to run , You can see it clearly .

As shown in the figure , I hit an endpoint when I first met it ,Debug After the mode runs , The program has printed out the contents of the decorator .

—— The above comes from 《 smooth Python》

Decorator to log

I have used this before , But there was a problem , When decorating a function in a class , Parameter errors often occur , Because the first parameter of a function in a class is always self, The parameters are often incorrect during execution , Here is a decorator function that I have successfully implemented , Can solve this problem .

# ecoding=utf-8
# Author: Weng Yanbin | Sven_Weng
# Email : [email protected]
# Web : http://wybblog.applinzi.com
import time
import functools
def log(func):
@functools.wraps(func)
def inner_methods(*args, **kwargs):
t0 = time.time()
result = func(*args, **kwargs)
t1 = time.time()
name = func.__name__
arg_list = []
if args:
arg_list.append(', '.join([str(arg) for arg in args]))
if kwargs:
pairs = ['{0}={1}'.format(k, w) for k, w in sorted(kwargs.items())]
arg_list.append(', '.join(pairs))
print "[{0}]func_name:{1},args:({2})".format(str(t1 - t0), name, arg_list)
return result
return inner_methods

This decorator is decorated , The name of the function to be executed , Print out all time of the participating in execution .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved