zoukankan      html  css  js  c++  java
  • 第十七天:装饰器

    一、概述

    • 用于管理和增强函数和类行为的代码
    • 提供一种在函数或类定义中插入自动运行代码的机制
    • 特点
      • 更明确的语法
      • 更高的代码可维护性
      • 更好的一致性

    二、编写

    1、函数基础

    • 将函数赋给变量
    • 将函数作为参数传递
    • 函数嵌套及跨域访问
    def greeting():
        def hello():
            return 'Hello'
        return hello
    greeting
    greeting()()
    
    <function __main__.greeting()>
    'Hello'
    
    def func_1():
        x = 10
        def func_2():
            x = 20
            return x + 10
        return func_2()
    func_1()
    
    30
    
    def func_1():
        x = 10
        def func_2():
            nonlocal x
            return x + 10
        return func_2()
    func_1()
    
    20
    

    2、函数定义装饰器

    def p_decorator(func):
        def wrapper(*args, **kwargs):
            return '<p>' + func(*args, **kwargs) + '</p>'
        return wrapper
    # @p_decorator 第一种添加装饰器的方法
    def get_text():
        return '欢迎学习'
    if __name__ == '__main__':
        html = p_decorator(get_text) #第二种添加装饰器的方法
        print(html())
    
    <p>欢迎学习</p>
    

    3、类定义装饰器

    • 不易用于类方法
    class P:
        def __init__(self,func):
            self.func = func
    
        def __call(self, *args, **kwargs):
            return '{' + self.func(*args, **kwargs) + '}'
    @P
    def get_text():
        return "欢迎"
    

    4、装饰器参数

    def tags(tag):
    	def tag_decorator(func):
    		def wrapper(*args, **kwargs):
    			return f'<{tag}>{func(*args, **kwargs)}</{tag}>'
    		return wrapper
    	return tag_decorator
    @tag('div')
    def get_text():
    	return "欢迎"
    
  • 相关阅读:
    matplotlib 学习总结
    数据获取,解析,存储等知识的学习总结
    python学习总结
    Mybatis Plus各种查询方法
    centos启动Nginx提示nginx: [emerg] still could not bind()
    vue只能本地跨域,线上跨域要后端弄
    小程序图片懒加载
    html直接引入vue.js
    vue监听浏览器关闭
    【算法】归并排序算法的编码和优化
  • 原文地址:https://www.cnblogs.com/linyk/p/11523939.html
Copyright © 2011-2022 走看看