第十七天:装饰器

一、概述

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

二、编写

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 "欢迎"
原文地址:https://www.cnblogs.com/linyk/p/11523939.html