lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

    • Python 基础

    • Python 数据库

    • 面向对象

    • Python Web

    • Python 进阶

      • 协程
      • 装饰器
      • decorator
        • 装饰器
      • filter
      • 列表生成式
      • 进程&线程
      • 生成器
      • 匿名函数
      • map&&reduce
      • venv
  • leetcode

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • python
  • 进阶
2024-06-09
目录

decorator

# 装饰器

# 简单使用

from functools import wraps
def a_new_decorator(func):

    @wraps(func)
    def wrapTheFunction():
        print('some action before func')
        func()
        print('some action after func')

    return wrapTheFunction

## @a_new_decorator
def func():
    print('func run')
    ## output wrapTheFunction
    print(func.__name__)

if __name__ == '__main__':
    nFunc = a_new_decorator(func)
    nFunc()
    ## func()

等价于下面

from functools import wraps
def a_new_decorator(func):

    @wraps(func)
    def wrapTheFunction():
        print('some action before func')
        func()
        print('some action after func')

    return wrapTheFunction

@a_new_decorator
def func():
    print('func run')
    ## output wrapTheFunction
    print(func.__name__)

if __name__ == '__main__':
    ## nFunc = a_new_decorator(func)
    ## nFunc()
    func()
  1. 装饰器可以看作返回函数的函数
  2. a_new_decorator, 返回内部创建函数wrapTheFunction
  3. func.__name__,输出的内部创建的函数名,一般可以加上 @wraps(func), 变成函数 func

# 当函数有参数


def singleton(cls):
    instance = {}

    def _singleton(*args, **kwargs):
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]

    return _singleton

  1. 这是一个单例模式的写法
#装饰器
装饰器
filter

← 装饰器 filter→

最近更新
01
lhl learn notes
02
filter
06-09
03
商业价值理解
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式