python-装饰器骗局

2024-04-04 18:58
文章标签 python 装饰 骗局

本文主要是介绍python-装饰器骗局,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

装 饰 器 骗 局

Python 函数装饰器:https://www.runoob.com/w3cnote/python-func-decorators.html
装饰器的本意:
加上装饰器—>除了自身功能还有被装饰的内容
不加装饰器—>只有自身的功能

先来看一个装饰器的使用范例:

#计算程序运算时间的装饰器 --- 需要有一个形参 接受待验证运行时间的函数
def get_time(func):def wrapper():import timestart = time.time()func()stop = time.time()print("执行时间", stop - start)return wrapper'''
怎么为对应的功能添加装饰器使用@语法糖  在被需要添加装饰器的功能上方 @装饰器的外部函数
'''
@get_time
def print_nine_table():for r in range(1, 10):for c in range(1, r + 1):print(f"{c} * {r} = {r*c}", end="\t")print()
print_nine_table()

在这里插入图片描述
在这里插入图片描述

装饰器----->原有函数功能增加 or 函数重构 ?

咱们先来看下 Python 中的函数的一些操作:

def hi(name="yasoob"):return "hi " + nameprint(hi())
# output: 'hi yasoob'# 我们甚至可以将一个函数赋值给一个变量,比如
greet = hi
# 我们这里没有在使用小括号,因为我们并不是在调用hi函数
# 而是在将它放在greet变量里头。我们尝试运行下这个print(greet())
# output: 'hi yasoob'# 如果我们删掉旧的hi函数,看看会发生什么!
del hi
print(hi())
# outputs: NameErrorprint(greet())
# outputs: 'hi yasoob'

在函数中定义函数:

def hi(name="yasoob"):print("now you are inside the hi() function")def greet():return "now you are in the greet() function"def welcome():return "now you are in the welcome() function"print(greet())print(welcome())print("now you are back in the hi() function")hi()
# output:now you are inside the hi() function
#       now you are in the greet() function
#       now you are in the welcome() function
#       now you are back in the hi() function# 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。
# 然后greet()和welcome()函数在hi()函数之外是不能访问的,比如:greet()
# outputs: NameError: name 'greet' is not defined

从函数中返回函数:

def hi(name="yasoob"):def greet():return "now you are in the greet() function"def welcome():return "now you are in the welcome() function"if name == "yasoob":return greetelse:return welcomea = hi()
print(a)
# outputs: <function greet at 0x7f2143c01500># 上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
# 现在试试这个print(a())
# outputs: now you are in the greet() function

将函数作为参数传给另一个函数:

def hi():return "hi yasoob!"def doSomethingBeforeHi(func):print("I am doing some boring work before executing hi()")print(func())doSomethingBeforeHi(hi)
# outputs:I am doing some boring work before executing hi()
#        hi yasoob!

装饰器实例:

def a_new_decorator(a_func):def wrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")return wrapTheFunctiondef a_function():print("I am the function which needs some decoration to remove my foul smell")a_function()
# outputs: "I am the function which needs some decoration to remove my foul smell"a_function =a_new_decorator(a_functionn)
# now a_function is wrapped by wrapTheFunction()a_function()
# outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

语法糖@:

@a_new_decorator
def a_function():"""Hey you! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")a_function()
# outputs: I am doing some boring work before executing a_func()
#         I am the function which needs some decoration to remove my foul smell
#         I am doing some boring work after executing a_func()# the @a_new_decorator is just a short way of saying:
a_function=  a_new_decorator(a_function)

重构的问题:函数被warpTheFunction替代了。它重写了我们函数的名字和注释文档(docstring)

print(a_function.__name__)
# Output: wrapTheFunction

functools.wraps的引入:

from functools import wrapsdef a_new_decorator(a_func):@wraps(a_func)def wrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")return wrapTheFunction
@a_new_decorator
def a_function():"""Hey yo! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")print(a_function.__name__)
# Output: a_function

综上所述:装饰器本质上是通过程序内容上的一系列操作,把某一个函数的函数体进行了重写,只是名称还是当初那个函数名称,对于计算机来说,只要函数名称一样就会执行相应的函数.

这篇关于python-装饰器骗局的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/876596

相关文章

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

一文详解Python如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D

Python函数作用域与闭包举例深度解析

《Python函数作用域与闭包举例深度解析》Python函数的作用域规则和闭包是编程中的关键概念,它们决定了变量的访问和生命周期,:本文主要介绍Python函数作用域与闭包的相关资料,文中通过代码... 目录1. 基础作用域访问示例1:访问全局变量示例2:访问外层函数变量2. 闭包基础示例3:简单闭包示例4

Python实现字典转字符串的五种方法

《Python实现字典转字符串的五种方法》本文介绍了在Python中如何将字典数据结构转换为字符串格式的多种方法,首先可以通过内置的str()函数进行简单转换;其次利用ison.dumps()函数能够... 目录1、使用json模块的dumps方法:2、使用str方法:3、使用循环和字符串拼接:4、使用字符

Python版本与package版本兼容性检查方法总结

《Python版本与package版本兼容性检查方法总结》:本文主要介绍Python版本与package版本兼容性检查方法的相关资料,文中提供四种检查方法,分别是pip查询、conda管理、PyP... 目录引言为什么会出现兼容性问题方法一:用 pip 官方命令查询可用版本方法二:conda 管理包环境方法

基于Python开发Windows自动更新控制工具

《基于Python开发Windows自动更新控制工具》在当今数字化时代,操作系统更新已成为计算机维护的重要组成部分,本文介绍一款基于Python和PyQt5的Windows自动更新控制工具,有需要的可... 目录设计原理与技术实现系统架构概述数学建模工具界面完整代码实现技术深度分析多层级控制理论服务层控制注

pycharm跑python项目易出错的问题总结

《pycharm跑python项目易出错的问题总结》:本文主要介绍pycharm跑python项目易出错问题的相关资料,当你在PyCharm中运行Python程序时遇到报错,可以按照以下步骤进行排... 1. 一定不要在pycharm终端里面创建环境安装别人的项目子模块等,有可能出现的问题就是你不报错都安装

Python打包成exe常用的四种方法小结

《Python打包成exe常用的四种方法小结》本文主要介绍了Python打包成exe常用的四种方法,包括PyInstaller、cx_Freeze、Py2exe、Nuitka,文中通过示例代码介绍的非... 目录一.PyInstaller11.安装:2. PyInstaller常用参数下面是pyinstal

Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题

《Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题》在爬虫工程里,“HTTPS”是绕不开的话题,HTTPS为传输加密提供保护,同时也给爬虫带来证书校验、... 目录一、核心问题与优先级检查(先问三件事)二、基础示例:requests 与证书处理三、高并发选型:

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数