zoukankan      html  css  js  c++  java
  • 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")
        


     

  • 相关阅读:
    设计模式 : Template method 模板方法模式 -- 行为型
    设计模式:Strategy 策略模式 -- 行为型
    没有评审的技术都是扯淡
    TCP/IP 协议大致的概念
    HTTP 2.0 与 tomcat
    相对URL拼接为绝对URL的过程
    URI与URL区别
    《淘宝首页性能优化实践》文章阅读
    第一章 Linux内核简介
    vim中执行shell命令小结
  • 原文地址:https://www.cnblogs.com/chenjianhong/p/4145120.html
Copyright © 2011-2022 走看看