23python装饰器的使用

               函数与方法的装饰器,这些可以实现面向切面的编程,类似于java的spring中的proxy

#-*-coding:UTF-8-*-
#修饰器会默认接受一个对象,用来确保运行后将控制权返回给原来的函数,参数是一个function对象
def dec(func):
    print '我是装饰器'
    return func


def dec1(func):
    print 'after'

class demo:
    @dec
    def fun1(self):
        print '我是方法!'
demo().fun1()


 对参数数量不确定的函数进行装饰

import pdb
pdb.set_trace()
def decorator(func):
	def before(*args,**kwargs):
		print 'before!'		
		func(*args,**kwargs)
		print 'after!'
		print args,kwargs
	return before

@decorator
def foo(a,b=2):
	print 'content'

if __name__ == '__main__':
	foo(1,b=2)


让装饰器带参数

import pdb
pdb.set_trace()
def decorator(a):
	def canshu(func):
		def before(*args,**kwargs):
			print 'before!'		
			func(*args,**kwargs)
			print 'after!'
			print args,kwargs,a
		return before
	return canshu
@decorator('123')
def foo(a,b=2):
	print 'content'

if __name__ == '__main__':
	foo(1,b=2)


与前面的不同在于:比上一层多了一层封装,先传递参数,再传递函数名。

def timer(b,d): #b,d为装饰器的参数
    def m(a):   #a是函数本身
        def t(c): #c是函数的参数
            print c
            print d
            print b
            a('ccc')
        return t
    return m    

@timer("this is the decorator's args",1)
def test(a):
    print a
    print 'main'
     

test("this is the function's args")
    


 

原文地址:https://www.cnblogs.com/chenjianhong/p/4145120.html