美文网首页
python语言之三:python装饰器

python语言之三:python装饰器

作者: Wu杰语 | 来源:发表于2018-06-18 18:26 被阅读0次

不带参数的装饰器

python装饰器也是python解释器下的一颗语法糖。形式上如下:

def mywraper(fun):
    def inner():
      do somethting
      fun()
   return inner

@mywraper
def myfun():
    dosomething

接着解释器出马了,执行myfun()的时候,会加上解释器的部分,把myfun变成 mywraper(fun)。

带参数的装饰器

def mywraper(paras):
    def inner(func):
       def inside():
          do somethting
          fun()
      return inside
   return inner

@mywraper(paras)
def myfun():
    dosomething

不带参数的和带参数的都使用了高阶函数的概念,所不同的是,带参数的比不带参数的多了一层函数作为返回值。

类装饰器

class A:
   # Decorator as an instance method
  def decorator1(self, func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print('Decorator 1')
            return func(*args, **kwargs)
        return wrapper

@classmethod
    def decorator2(cls, func):  
    @wraps(func)
    def wrapper(*args, **kwargs):
        print('Decorator 2')
        return func(*args, **kwargs)
    return wrapper

 用法上
a = A()
@a.decorator
 def myfun():

@A.decorator2
def myfun()

装饰器放在类中最典型的例子是Property,Porperty是个函数装饰器,python解释器将这个被property装饰的函数名字变成一个propery成员,接着可以用@name.setter @name.getter这两个类装饰器。

装饰器的作用很强大,但是要清楚这是语法糖,不要被语法糖所迷惑。

相关文章

  • 2022-10-27

    10个美妙的Python装饰器对Python编程语言中我最喜欢的一些装饰器的概述。 简介 关于Python编程...

  • python语言之三:python装饰器

    不带参数的装饰器 python装饰器也是python解释器下的一颗语法糖。形式上如下: 接着解释器出马了,执行my...

  • python 装饰器

    一、我们在python语言中常用@classmethod、@staticmethod这个装饰器,装饰器的作用简单来...

  • 装饰器模式

    介绍 在python装饰器学习 这篇文章中,介绍了python 中的装饰器,python内置了对装饰器的支持。面向...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • python中的装饰器

    python装饰器详解 Python装饰器学习(九步入门) 装饰器(decorator) 就是一个包装机(wrap...

  • TypeScript: 类的装饰器(三)

    带参数的类的装饰器 学习 python 的同学应该知道,python 中也有装饰器,而且 python 中的众多框...

  • 2018-07-18

    Python装饰器 装饰,顾名思义,是用来打扮什么东西的。Python装饰...

  • [译] Python装饰器Part II:装饰器参数

    这是Python装饰器讲解的第二部分,上一篇:Python装饰器Part I:装饰器简介 回顾:不带参数的装饰器 ...

  • 2018-02-05

    python @property装饰器

网友评论

      本文标题:python语言之三:python装饰器

      本文链接:https://www.haomeiwen.com/subject/sobneftx.html