Python----装饰器的使用方法

简介: Python----装饰器的使用方法

【原文链接】

根据装饰器和被装饰对象的不同类型,装饰器的使用场景主要有以下情况

  • 装饰器是函数,

    • 被装饰对象也是函数

      • 装饰器无参数,被装饰对象无参数
      • 装饰器无参数,被装饰对象有参数
      • 装饰器有参数,被装饰对象无参数
      • 装饰器有参数,被装饰器对象有参数
    • 被装饰对象是类

      • 装饰器无参数,被装饰类无参数
      • 装饰器无参数,被装饰类有参数
      • 装饰器有参数,被装饰类无参数
      • 装饰器有参数,被装饰类有参数
    • 被装饰对象是类中的方法

      • 装饰器无参数,被装饰类中的方法无参数
      • 装饰器无参数,被装饰类中的方法有参数
      • 装饰器有参数,被装饰类中的方法无参数
      • 装饰器有参数,被装饰类中的方法有参数
  • 装饰器是类

    • 被装饰对象也是函数

      • 装饰器无参数,被装饰对象无参数
      • 装饰器无参数,被装饰对象有参数
      • 装饰器有参数,被装饰对象无参数
      • 装饰器有参数,被装饰器对象有参数
    • 被装饰器对象是类

      • 装饰器无参数,被装饰类无参数
      • 装饰器无参数,被装饰类有参数
      • 装饰器有参数,被装饰类无参数
      • 装饰器有参数,被装饰类有参数
    • 被装饰对象是类中的方法

      • 装饰器无参数,被装饰类中的方法无参数
      • 装饰器无参数,被装饰类中的方法有参数
      • 装饰器有参数,被装饰类中的方法无参数
      • 装饰器有参数,被装饰类中的方法有参数

实例演示不同场景下的装饰器

  • 装饰器是函数,

    • 被装饰对象也是函数
      装饰器是函数,被装饰对象是函数时,此时装饰器的作用是给被装饰对象的函数做功能增强功能,思想是面向切面编程思想,即在被装饰对象的函数的之前和之后做一些额外处理,而不破坏被装饰函数原有的功能实现,主要有以下几种情况:

      • 装饰器无参数,被装饰对象无参数

        def decorator(func):
            def _decorator():
                print("before func......")
                func()
                print("after func......")
            return _decorator
        
        @decorator
        def func():
            print("in func()......")
        
        func()    

        执行结果为:

        before func......
        in func()......
        after func......
      • 装饰器无参数,被装饰对象有参数

        def decorator(func):
            def _decorator(*args,**kwargs):
                print("before {name}......".format(name=func.__name__))
                func(*args,**kwargs)
                print("after {name}......".format(name=func.__name__))
            return _decorator
        
        @decorator
        def func1():
            print("in func1()......")
        
        @decorator
        def func2(a,b):
            print("in func2()......")
            print("a={a},b={b}".format(a=a,b=b))
        
        @decorator
        def func3(a,b,c=10):
            print("in func3()......")
            print("a={a},b={b}".format(a=a, b=b))
            print("c={c}".format(c=c))
        
        func1()
        func2(1,2)
        func3(1,2,c=100)

        运行结果为:

        before func1......
        in func1()......
        after func1......
        before func2......
        in func2()......
        a=1,b=2
        after func2......
        before func3......
        in func3()......
        a=1,b=2
        c=100
        after func3......
      • 装饰器有参数,被装饰对象无参数

        def wrapper(name):
            def decorator(func):
                def _decorator():
                    print("before {name} ,decorator param is {param}".format(name=func.__name__,param=name))
                    print("before {name}......".format(name=func.__name__))
                    func()
                    print("after {name}......".format(name=func.__name__))
                return _decorator
            return decorator
        
        @wrapper(name="hello world")
        def func1():
            print("in func1()......")
        
        func1()

        运行结果为:

        before func1 ,decorator param is hello world
        before func1......
        in func1()......
        after func1......
      • 装饰器有参数,被装饰器对象有参数

        def wrapper(name):
            def decorator(func):
                def _decorator(*args,**kwargs):
                    print("before {name} ,decorator param is {param}".format(name=func.__name__,param=name))
                    print("before {name}......".format(name=func.__name__))
                    func(*args,**kwargs)
                    print("after {name}......".format(name=func.__name__))
                return _decorator
            return decorator
        
        @wrapper(name="hello world")
        def func1():
            print("in func1()......")
        
        @wrapper(name="hello world")
        def func2(a, b):
            print("in func2()......")
            print("a={a},b={b}".format(a=a, b=b))
        
        @wrapper(name="hello world")
        def func3(a, b, c=10):
            print("in func3()......")
            print("a={a},b={b}".format(a=a, b=b))
            print("c={c}".format(c=c))
        
        func1()
        func2(1,2)
        func3(1,2,c=100)

        运行结果如下:

        before func1 ,decorator param is hello world
        before func1......
        in func1()......
        after func1......
        before func2 ,decorator param is hello world
        before func2......
        in func2()......
        a=1,b=2
        after func2......
        before func3 ,decorator param is hello world
        before func3......
        in func3()......
        a=1,b=2
        c=100
        after func3......
    • 被装饰器对象是类
      被装饰器对象为类时,装饰器的作用是类在初始化的时候做功能增强,即可以在类初始化之前或者之后做一些功能增强,所以下面所说的被装饰对象有无参数是针对类的初始化函数__init__有无参数而言的,主要有以下几种情况:

      • 装饰器无参数,被装饰类无参数

        def decorator(cls):
            def _decorator():
                print("before class {name} init......".format(name=cls.__name__))
                obj=cls()
                print("after class {name} init......".format(name=cls.__name__))
                return obj
            return _decorator
        
        @decorator
        class Test(object):
            def __init__(self):
                print("in class {name} init function......".format(name=Test.__name__))
        
            def func(self):
                print("in class {name} func()".format(name=Test.__name__))
        
        test=Test()
        
        test.func()

        运行结果如下:

        before class Test init......
        in class _decorator init function......
        after class Test init......
        in class _decorator func()
      • 装饰器无参数,被装饰类有参数

        def decorator(cls):
            def _decorator(*args,**kwargs):
                print("before class {name} init......".format(name=cls.__name__))
                obj=cls(*args,**kwargs)
                print("after class {name} init......".format(name=cls.__name__))
                return obj
            return _decorator
        
        @decorator
        class Test(object):
            def __init__(self,a,b=10):
                print("in class {name} init function......".format(name=Test.__name__))
                print("a={a},b={b}".format(a=a,b=b))
        
            def func(self):
                print("in class {name} func()".format(name=Test.__name__))
        
        test=Test(2,20)
        
        test.func()

        执行结果如下:

        before class Test init......
        in class _decorator init function......
        a=2,b=20
        after class Test init......
        in class _decorator func()
      • 装饰器有参数,被装饰类无参数

        def wrapper(name="hello world"):
            def decorator(cls):
                def _decorator():
                    print("before class {name} init......".format(name=cls.__name__))
                    obj=cls()
                    print("after class {name} init......".format(name=cls.__name__))
                    return obj
                return _decorator
            return decorator
        
        @wrapper("hello world")
        class Test(object):
            def __init__(self):
                print("in class {name} init function......".format(name=Test.__name__))
        
            def func(self):
                print("in class {name} func()".format(name=Test.__name__))
        
        test=Test()
        
        test.func()

        执行结果如下:

        before class Test init......
        in class _decorator init function......
        after class Test init......
        in class _decorator func()
      • 装饰器有参数,被装饰类有参数

        def wrapper(name="hello world"):
            def decorator(cls):
                def _decorator(*args,**kwargs):
                    print("before class {name} init......".format(name=cls.__name__))
                    obj=cls(*args,**kwargs)
                    print("after class {name} init......".format(name=cls.__name__))
                    return obj
                return _decorator
            return decorator
        
        @wrapper("hello world")
        class Test(object):
            def __init__(self,a,b=10):
                print("in class {name} init function......".format(name=Test.__name__))
                print("a= {a} b={b}".format(a=a,b=b))
        
            def func(self):
                print("in class {name} func()".format(name=Test.__name__))
        
        test=Test(2,b=20)
        
        test.func()
        ``
        运行结果如下:

        before class Test init......
        in class _decorator init function......
        a= 2 b=20
        after class Test init......
        in class _decorator func()

    • 被装饰对象是类中的方法

      • 装饰器无参数,被装饰类中的方法无参数

        def decorator(func):
            def _decorator(self):
                print("before class {name} init......".format(name=func.__name__))
                obj=func(self)
                print("after class {name} init......".format(name=func.__name__))
                return obj
            return _decorator
        
        class Test(object):
            def __init__(self,a=1,b=10):
                self.a=a
                self.b=b
            @decorator
            def func(self):
                print("in class {name} func()".format(name=Test.__name__))
                print("a={a} b={b}".format(a=self.a,b=self.b))
        
        test=Test()
        
        test.func()

        执行结果如下:

        before class func init......
        in class Test func()
        a=1 b=10
        after class func init......
      • 装饰器无参数,被装饰类中的方法有参数

        
        def decorator(func):
            def _decorator(self,*args,**kwargs):
                print("before class {name} init......".format(name=func.__name__))
                obj=func(self,*args,**kwargs)
                print("after class {name} init......".format(name=func.__name__))
                return obj
            return _decorator
        
        class Test(object):
            def __init__(self,a=1,b=10):
                self.a=a
                self.b=b
            @decorator
            def func(self,c,d=20):
                print("in class {name} func()".format(name=Test.__name__))
                print("a={a} b={b}".format(a=self.a,b=self.b))
                print("c={c} d={d}".format(c=c,d=d))
        
        test=Test()
        
        test.func(2,d=20)

        执行结果如下:

        before class func init......
        in class Test func()
        a=1 b=10
        c=2 d=20
        after class func init......
      • 装饰器有参数,被装饰类中的方法无参数

        
        def wrapper(name="hello world"):
            def decorator(func):
                def _decorator(self):
                    print("before class {name} init......".format(name=func.__name__))
                    print("name = {name}".format(name=name))
                    obj=func(self)
                    print("after class {name} init......".format(name=func.__name__))
                    return obj
                return _decorator
            return decorator
        
        class Test(object):
            def __init__(self,a=1,b=10):
                self.a=a
                self.b=b
            @wrapper(name="Test.func")
            def func(self):
                print("in class {name} func()".format(name=Test.__name__))
                print("a={a} b={b}".format(a=self.a,b=self.b))
        
        test=Test()
        
        test.func()

        执行结果如下:

        before class func init......
        name = Test.func
        in class Test func()
        a=1 b=10
        after class func init......
      • 装饰器有参数,被装饰类中的方法有参数

        def wrapper(name="hello world"):
            def decorator(func):
                def _decorator(self,*args,**kwargs):
                    print("before class {name} init......".format(name=func.__name__))
                    print("name = {name}".format(name=name))
                    obj=func(self,*args,**kwargs)
                    print("after class {name} init......".format(name=func.__name__))
                    return obj
                return _decorator
            return decorator
        
        class Test(object):
            def __init__(self,a=1,b=10):
                self.a=a
                self.b=b
            @wrapper(name="Test.func")
            def func(self,c,d=20):
                print("in class {name} func()".format(name=Test.__name__))
                print("a={a} b={b}".format(a=self.a,b=self.b))
                print("c={c} d={d}".format(c=c,d=d))
        
        test=Test()
        
        test.func(2,d=20)
        ``
        执行结果如下:

        before class func init......
        name = Test.func
        in class Test func()
        a=1 b=10
        c=2 d=20
        after class func init......

  • 装饰器是类

    • 被装饰对象是函数

    装饰器是类,被装饰对象是函数的时候,是通过装饰器类初始化的时候将被装饰对象函数传递给装饰器类,然后通过自动调用装饰器类中的__call__函数实现对被装饰对象的前后处理,即在这种情况下,只需要在__call__函数中编写在调用被装饰对象前后进行操作的代码即可

    • 装饰器无参数,被装饰对象无参数

      class decorator(object):
          def __init__(self,func):
              self.func=func
      
          def __call__(self):
              print("before func {func}()...".format(func=self.func.__name__))
              result=self.func()
              print("after func {func}()...".format(func=self.func.__name__))
              return result
      
      @decorator
      def func():
          print("in func func()...")
      
      func()

      执行结果如下:

      before func func()...
      in func func()...
      after func func()...
    • 装饰器无参数,被装饰对象有参数

      class decorator(object):
          def __init__(self,func):
              self.func=func
      
          def __call__(self,*args,**kwargs):
              print("before func {func}()...".format(func=self.func.__name__))
              result=self.func(*args,**kwargs)
              print("after func {func}()...".format(func=self.func.__name__))
              return result
      
      @decorator
      def func(a,b=10):
          print("in func func()...")
          print("a= {a} b={b}".format(a=a,b=b))
      
      func(2,b=20)
      ``
      执行结果如下:

      before func func()...
      in func func()...
      a= 2 b=20
      after func func()...

    • 装饰器有参数,被装饰对象无参数

      
      class decorator(object):
          def __init__(self,name="hello world"):
              self.name=name
      
          def __call__(self,func):
              def wrapper():
                  print("before func {func}()...".format(func=func.__name__))
                  print("name= {name}".format(name=self.name))
                  result=func()
                  print("after func {func}()...".format(func=func.__name__))
                  return result
              return wrapper
      
      @decorator()
      def func1():
          print("in func func2()...")
      
      @decorator("func2_decorator")
      def func2():
          print("in func func2()...")
      
      @decorator(name="func3_decorator")
      def func3():
          print("in func func3()...")
      
      func1()
      
      func2()
      
      func3()

      执行结果如下:

      before func func1()...
      name= hello world
      in func func2()...
      after func func1()...
      before func func2()...
      name= func2_decorator
      in func func2()...
      after func func2()...
      before func func3()...
      name= func3_decorator
      in func func3()...
      after func func3()...
    • 装饰器有参数,被装饰器对象有参数

      
      class decorator(object):
          def __init__(self,name="hello world"):
              self.name=name
      
          def __call__(self,func):
              def wrapper(*args,**kwargs):
                  print("before func {func}()...".format(func=func.__name__))
                  print("name= {name}".format(name=self.name))
                  result=func(*args,**kwargs)
                  print("after func {func}()...".format(func=func.__name__))
                  return result
              return wrapper
      
      @decorator()
      def func1():
          print("in func func2()...")
      
      @decorator("func2_decorator")
      def func2(a):
          print("in func func2()...")
          print("a={a}".format(a=a))
      
      @decorator(name="func3_decorator")
      def func3(a,b=10):
          print("in func func3()...")
          print("a={a}, b= {b}".format(a=a,b=b))
      
      func1()
      
      func2(10)
      
      func3(2,b=20)

      执行结果如下:

      before func func1()...
      name= hello world
      in func func2()...
      after func func1()...
      before func func2()...
      name= func2_decorator
      in func func2()...
      a=10
      after func func2()...
      before func func3()...
      name= func3_decorator
      in func func3()...
      a=2, b= 20
      after func func3()...
    • 被装饰器对象是类

      • 装饰器无参数,被装饰类无参数

        class decorator(object):
            def __init__(self,cls):
                self.cls=cls
        
            def __call__(self):
                print("before init clsss {cls}...".format(cls=self.cls.__name__))
                obj=self.cls()
                print("after init class {cls}...".format(cls=self.cls.__name__))
                return obj
        
        @decorator
        class Test():
            def __init__(self):
                print("in Test class __init__ func...")
        
            def test(self):
                print("in Test class test func...")
        
        t=Test()
        t.test()

        执行结果如下:

        before init clsss Test...
        in Test class __init__ func...
        after init class Test...
        in Test class test func...
      • 装饰器无参数,被装饰类有参数

        class decorator(object):
            def __init__(self,cls):
                self.cls=cls
        
            def __call__(self,*args,**kwargs):
                print("before init clsss {cls}...".format(cls=self.cls.__name__))
                obj=self.cls(*args,**kwargs)
                print("after init class {cls}...".format(cls=self.cls.__name__))
                return obj
        
        @decorator
        class Test():
            def __init__(self,a,b=10):
                print("in Test class __init__ func...")
                print("a={a} b={b}".format(a=a,b=b))
        
            def test(self):
                print("in Test class test func...")
        
        t=Test(2,b=20)
        t.test()

        执行结果如下:

        before init clsss Test...
        in Test class __init__ func...
        a=2 b=20
        after init class Test...
        in Test class test func...
      • 装饰器有参数,被装饰类无参数

        class decorator(object):
            def __init__(self,name="hello world"):
                self.name=name
        
            def __call__(self,cls):
                def wrapper():
                    print("before init class {cls}....".format(cls=cls.__name__))
                    obj=cls()
                    print("after init class {cls}...".format(cls=cls.__name__))
                    return obj
                return wrapper
        
        @decorator(name="Test Class")
        class Test():
            def __init__(self):
                print("in Test class __init__ func...")
        
            def test(self):
                print("in Test class test func...")
        
        t=Test()
        t.test()

        执行结果如下:

        before init class Test....
        in Test class __init__ func...
        after init class Test...
        in Test class test func...
      • 装饰器有参数,被装饰类有参数

        class decorator(object):
            def __init__(self,name="hello world"):
                self.name=name
        
            def __call__(self,cls):
                def wrapper(*args,**kwargs):
                    print("before init class {cls}....".format(cls=cls.__name__))
                    obj=cls(*args,**kwargs)
                    print("after init class {cls}...".format(cls=cls.__name__))
                    return obj
                return wrapper
        
        @decorator(name="Test Class")
        class Test():
            def __init__(self,a,b=10):
                print("in Test class __init__ func...")
                print("a={a}, b={b}".format(a=a,b=b))
        
            def test(self):
                print("in Test class test func...")
        
        t=Test(2,b=20)
        t.test()

        执行结果如下:

        before init class Test....
        in Test class __init__ func...
        a=2, b=20
        after init class Test...
        in Test class test func...
    • 被装饰对象是类中的方法

      • 装饰器无参数,被装饰类中的方法无参数

        class decorator(object):
            def __init__(self,func):
                self.func=func
        
            def __call__(self):
                print("before func {func}...".format(func=self.func.__name__))
                results=self.func(self)
                print("after func {func}...".format(func=self.func.__name__))
                return results
        
        class Test():
            def __init__(self):
                print("in Test class __init__ func...")
        
            @decorator
            def test(self):
                print("in Test class test func...")
        
        t=Test()
        t.test()

        执行结果如下:

        in Test class __init__ func...
        before func test...
        in Test class test func...
        after func test...
      • 装饰器无参数,被装饰类中的方法有参数
        ``python
        class decorator(object):

        def __init__(self,func):
            self.func=func
        
        def __call__(self,*args,**kwargs):
            print("before func {func}...".format(func=self.func.__name__))
            results=self.func(self,*args,**kwargs)
            print("after func {func}...".format(func=self.func.__name__))
            return results
        

        class Test():

        def __init__(self):
            print("in Test class __init__ func...")
        
        @decorator
        def test(self,a,b=10):
            print("in Test class test func...")
            print("a={a}  b={b}".format(a=a,b=b))
        

        t=Test()
        t.test(2,b=20)

        执行结果如下:

        in Test class init func...
        before func test...
        in Test class test func...
        a=2 b=20
        after func test...

      • 装饰器有参数,被装饰类中的方法无参数

        class decorator(object):
            def __init__(self,name="hello world"):
                self.name=name
        
            def __call__(self,func):
                def wrapper(self):
                    print("before func {func}...".format(func=func.__name__))
                    results=func(self)
                    print("after func {func}...".format(func=func.__name__))
                    return results
                return wrapper
        
        class Test():
            def __init__(self):
                print("in Test class __init__ func...")
        
            @decorator(name="Test_test")
            def test(self):
                print("in Test class test func...")
        
        t=Test()
        t.test()

        执行结果如下:

        in Test class __init__ func...
        before func test...
        in Test class test func...
        after func test...
      • 装饰器有参数,被装饰类中的方法有参数

        class decorator(object):
            def __init__(self,name="hello world"):
                self.name=name
        
            def __call__(self,func):
                def wrapper(self,*args,**kwargs):
                    print("before func {func}...".format(func=func.__name__))
                    results=func(self,*args,**kwargs)
                    print("after func {func}...".format(func=func.__name__))
                    return results
                return wrapper
        
        class Test():
            def __init__(self):
                print("in Test class __init__ func...")
        
            @decorator(name="Test_test")
            def test(self,a,b=10):
                print("in Test class test func...")
                print("a={a}, b={b}".format(a=a,b=b))
        
        t=Test()
        t.test(2,b=20)

        执行结果如下:

        in Test class __init__ func...
        before func test...
        in Test class test func...
        a=2, b=20
        after func test...
目录
相关文章
|
3天前
|
缓存 开发者 Python
Python中的装饰器:提升代码灵活性与可复用性
众所周知,Python作为一门流行的编程语言,其装饰器(Decorator)机制为代码的优化和重用提供了强大支持。本文将深入探讨Python中装饰器的概念、用法和实际应用,帮助读者更好地理解并应用这一技术,从而提升代码的灵活性和可复用性。
|
3天前
|
缓存 Python
Python中的装饰器应用及实践
Python中的装饰器是一种强大的编程工具,它可以在不更改原函数代码的情况下,对函数进行扩展和修改。本文将介绍装饰器的基本概念,探讨其在Python开发中的实际应用,并结合示例代码进行详细解析。
|
3天前
|
缓存 测试技术 Python
Python中的装饰器应用探究
在Python编程中,装饰器是一种强大而灵活的工具,它可以用于修改、包装和增强函数或方法的行为。本文将深入探讨Python中装饰器的应用,包括装饰器的基本概念、实际应用场景以及一些高级技巧,帮助读者更好地理解和运用这一重要的编程技术。
|
3天前
|
程序员 开发者 Python
Python中的装饰器:优雅而强大的函数修饰工具
在Python编程中,装饰器是一种强大的工具,它可以简洁地实现函数的增强、扩展和重用。本文将深入探讨Python中装饰器的工作原理、常见应用场景以及如何自定义装饰器,帮助读者更好地理解和运用这一重要的编程概念。
|
3天前
|
缓存 开发者 Python
Python中的装饰器:提升代码灵活性和可维护性
Python中的装饰器是一种强大的工具,它可以帮助开发者提升代码的可维护性和灵活性。本文将深入探讨Python装饰器的原理、用法以及实际应用场景,帮助读者更好地理解并运用装饰器来优化自己的代码。
|
4天前
|
缓存 Python
Python中的装饰器:优雅而强大的函数装饰技术
在Python编程中,装饰器是一种强大而灵活的技术,它可以使函数具有额外的功能,而不需要改变函数的核心代码。本文将深入探讨装饰器的原理、用法以及实际应用场景,帮助读者更好地理解和利用这一重要的Python编程工具。
|
6天前
|
测试技术 Python
解密Python中的装饰器:提升代码可读性与灵活性
Python中的装饰器是一种强大的工具,能够在不改变原有函数结构的情况下,为函数添加额外功能。本文将深入探讨装饰器的原理及应用,介绍装饰器的基本语法和常见用法,并结合实例演示如何利用装饰器提升代码的可读性和灵活性,使代码更加简洁、模块化和易于维护。
|
6天前
|
监控 Python
Python中的装饰器:提升代码灵活性和可维护性
在Python编程中,装饰器是一种强大的工具,可以提高代码的灵活性和可维护性。本文将深入探讨装饰器的概念、用法和实际应用,帮助读者更好地理解并运用装饰器来优化自己的Python代码。
|
6天前
|
Python
Python中的装饰器:提升代码可读性与复用性
Python中的装饰器是一种强大的工具,能够提升代码的可读性和复用性。本文将深入探讨装饰器的原理、用法以及在实际项目中的应用,帮助读者更好地理解和利用这一特性,提升代码质量和开发效率。
|
6天前
|
监控 Python
Python中的装饰器:提升代码可读性与可维护性
Python中的装饰器是一种强大的工具,可以在不修改函数源代码的情况下,增加新的功能。本文将介绍装饰器的基本概念,以及如何使用装饰器来提升代码的可读性和可维护性。通过实例演示,读者将了解装饰器在各种场景下的灵活运用,从而更好地理解并应用于实际开发中。