DarkTime
  • README
  • SpringBoot
    • spring boot 运维
    • Spring Boot 部署war包
    • springboot搭建
    • spring boot 读取配置文件
    • 简单总结
    • spring配置文件
    • spring boot Configuration
    • spring boot 配置文件
    • spring boot 配置mybatis
  • MacAwesome
    • markdown使用
    • MAC APP Awesome
    • [markdown使用](/MacAwesome/SUMMARY.md)
    • chrome
    • intellij idea
    • MacAwesome
    • VS Code 的使用
    • MAC Shell命令
  • database
    • druid使用
  • 框架
    • 项目拆析
    • 各种框架和工具
  • docker
    • kubernetes
    • docker
    • docker 常用镜像
  • 效率工具
    • 解决dns污染导致域名解析失败
    • sonarqube 相关配置
    • Iterm2 使用
    • gitbook
    • github awesome github资源推荐
    • playground 在线试用平台汇总
    • linux中的office
    • linux screen 工具
    • 简单Mock服务(moco)
    • npm
    • Visual Studio Code 的使用
    • 配置开发环境
    • homebrew的使用
    • 汇总
  • tomcat
    • tomcat目录规范
  • code_snippets
  • 专题
    • RESTful API
    • serveless服务
    • 搭建私有云主机 折腾记
    • 开发中的各种疑难杂症问题
    • spring 最佳实践
    • LLM 大语言模型
    • notelive
      • 文章框架
      • notelive vue版本开发
      • notelive 开发 札记
    • webrtc技术分析
    • 反向代理
    • spring-cloud
      • spring boot admin 监控服务
      • Spring Cloud 整理汇总
  • python
    • python 学习
    • Python 修饰器的一些小细节
  • 云主机
    • aliyun 主机的种种
  • maven
    • maven使用
    • maven项目增加编译版本号 buildnumber-maven-plugin
    • 仓库
  • java
    • java 开发常用工具类
    • java
    • apache commons pool 对象连接池
  • 大数据
    • kafka
    • gobblin
    • sqoop 简介及使用
    • hbase
    • gobblin
    • sqoop源码解析
    • hadoop map reduce
    • 大数据 学习札记
  • 脚本
    • python
      • 批量请求url 解析json数据
    • js
      • sheetjs-js读取excel
    • shell
      • 自动生成bitbook的summary文件
      • linux/mac 实用脚本
      • 自动创建tomcat项目脚本
      • 批量处理文件内容脚本
  • nginx
    • nginx
    • ngix 文件浏览器 文件服务器
  • linux
    • 群晖nas札记
    • ftp
    • linux 运维
    • 常用命令
    • linux
    • mysqldump脚本
    • 代理
    • 简易灰度部署脚本 不使用jenkins的纯shell方式
    • shell脚本
    • 附加文档
  • mysql
    • sql
  • 游戏开发
    • Unity 2020 学习笔记
  • 学习笔记
    • centos常用环境安装
    • gradle 学习
    • 建站经历
    • python
      • 爬虫教程
    • 如何解决百度爬虫无法爬取搭建在Github上的个人博客的问题? - 知乎
    • baas
      • 在本地部署Parse Server
    • mysql学习标记
    • java code snippets
    • 非Spring Boot Web项目 注册节点到Eureka Server并提供服务
    • kotlin
      • Kotlin 学习札记
    • spring cloud
    • vim配置
    • 前端
      • 开发PWA应用
  • jenkins
    • jenkins配置备份
    • gitlab触发Jenkins 自动构建
    • 安装与使用
  • npm
    • npm 使用
  • git
    • ignore
    • git使用总结
    • git配置多个远程仓库
  • 前端
    • swig
    • 解决跨域请求问题
    • angularjs 学习
    • scriptbot的前端开发经验总结
    • 各种资源
    • 一些有用的js代码
Powered by GitBook
On this page

Was this helpful?

  1. python

Python 修饰器的一些小细节

Previouspython 学习Next云主机

Last updated 6 years ago

Was this helpful?

"""
带参数修饰器会在初始化时就执行修饰器的代码并将方法体重新赋值给方法名。
"""


def deco1(args):
    """
    方法执行时不会再执行修饰器代码,**因为该代码返回了方法本身**
    等价于:
        def deco1(args):
            print("deco1:",args)
            return lambda fn:fn
        test1=deco1(args='deco1args')(mymethod)
    :param args:
    :return:
    """

    def decorator(fn):
        print('deco1:', args)
        return fn

    return decorator


@deco1("deco1args")
def test1():
    print("test1")


"""
不带参数修饰器在初始化的时候会将方法名赋值给修饰器方法,修饰器方法内部来手动调用被修饰的方法。
"""


def deco2(fn):
    """
    方法每次执行时都会执行修饰器因为 test2 重新赋值为修饰器的函数
    等价于:
        def deco2(fn):
            def inFn():
                print('deco2')
                fn()
            return inFn
        myMethod2 = deco2(lambda: print("call myMethod2"))
    :param fn:
    :return:
    """

    def decorator():
        print('deco2')
        fn()

    return decorator


@deco2
def test2():
    print("test2")


def deco3(fn):
    """
    不会执行 fn 因为 fn 没有被调用
    等价于:
        def deco3(fn):
            def inFn():
                print('deco3')
                return fn
            return inFn
        test3=deco3(test3)

    :return:
    """

    def decorator():
        print('deco3')
        return fn

    return decorator


@deco3
def test3():
    print("test3")


if __name__ == '__main__':
    print("-----开始执行 main 方法-----")

    print("test1 每次调用都不会执行修饰器:")
    test1()
    print("")
    test1()

    print("======")
    print("test2 每次调用都会执行修饰器:")
    test2()
    print("")
    test2()
    print("======")
    print("test3 不会被执行:")
    test3()
    print("test3 的返回值才是 test3 方法,因此要这样执行:")
    test3()()

"""
---------
"""

print("-------等价函数------")


def eqDeco1(args):
    print("deco1:", args)
    return lambda fn: fn


print("deco1 的等价:")

myMethod = eqDeco1(args='deco1args')(lambda: print("call myMethod1"))
myMethod()


def eqDeco2(fn):
    def inFn():
        print('deco2')
        fn()

    return inFn


myMethod2 = eqDeco2(lambda: print("call myMethod2"))
myMethod2()


def eqDeco3(fn):
    def inFn():
        print('deco3')
        return fn

    return inFn


myMethod3 = eqDeco3(lambda: print("call myMethod3"))
myMethod3()
myMethod3()()

执行结果

deco1: deco1args
-----开始执行 main 方法-----
test1 每次调用都不会执行修饰器:
test1

test1
======
test2 每次调用都会执行修饰器:
deco2
test2

deco2
test2
======
test3 不会被执行:
deco3
test3 的返回值才是 test3 方法,因此要这样执行:
deco3
test3
-------等价函数------
deco1 的等价:
deco1: deco1args
call myMethod1
deco2
call myMethod2
deco3
deco3
call myMethod3

在Django中实现flask的修饰器注册url映射

目录结构

django_school
├── __init__.py
├── controller
│   ├── __init__.py
│   ├── test.py
│   └── test2.py
├── settings.py
├── urls.py
└── wsgi.py

在url.py文件中创建修饰器,并import用到修饰器的方法以触发修饰器代码执行

# url.py
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls)
]

# 创建修饰器
def route(url_path):
    def add(fn):
        urlpatterns.append(path(url_path, fn))
        return fn

    return add

# import文件 执行修饰器
from django_school.controller import test,test2

具体使用的代码

# controller.test1.py
from django.http import HttpResponse
from django_school.urls import route

@route("demo1/")
def index1(request):
    return HttpResponse("this is demo1")
Python 修饰器的一些小细节 - V2EX