政安晨:示例演绎Python的函数与获取帮助的方法
调用函数和定义我们自己的函数,并使用Python内置的文档,是成为一位Pythoner的开始。
通过我的上篇文章,相信您已经看过并使用了print和abs等函数。但是Python还有许多其他函数,并且定义自己的函数是Python编程的重要部分。
在本课程中,你将学习更多关于使用和定义函数的知识。
获取帮助信息
你在上一篇教程中看到了abs函数,但如果你忘记了它做什么怎么办?
help()函数可能是你能学到的最重要的Python函数。如果你记得如何使用help(),你就掌握了理解大多数其他函数的关键。
以下是一个示例:
help(round)
执行如下(Python 3.11.7):
这里,help()会显示两件事情:
1.该函数round(number, ndigits=None)实现的头部注释信息。
这信息里告诉我们round()接受一个我们可以描述为number的参数。此外,我们可以选择性地提供一个独立的参数,可以描述为ndigits。
2. 该函数所做的功能的简要英文描述。
常见问题:当你查找一个函数时,记得传入的是函数本身的名称,而不是调用该函数的结果。
如果我们在调用函数round()上使用help会发生什么?解开下面单元格的输出以查看结果。
help(round(-2.01))
刚刚显示的完整的详细信息见下面:
Help on int object:class int(object)| int([x]) -> integer| int(x, base=10) -> integer| | Convert a number or string to an integer, or return 0 if no arguments| are given. If x is a number, return x.__int__(). For floating point| numbers, this truncates towards zero.| | If x is not a number or if base is given, then x must be a string,| bytes, or bytearray instance representing an integer literal in the| given base. The literal can be preceded by '+' or '-' and be surrounded| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.| Base 0 means to interpret the base from the string as an integer literal.| >>> int('0b100', base=0)| 4| | Built-in subclasses:| bool| | Methods defined here:| | __abs__(self, /)| abs(self)| | __add__(self, value, /)| Return self+value.| | __and__(self, value, /)| Return self&value.| | __bool__(self, /)| True if self else False| | __ceil__(...)| Ceiling of an Integral returns itself.| | __divmod__(self, value, /)| Return divmod(self, value).| | __eq__(self, value, /)| Return self==value.| | __float__(self, /)| float(self)| | __floor__(...)| Flooring an Integral returns itself.| | __floordiv__(self, value, /)| Return self//value.| | __format__(self, format_spec, /)| Default object formatter.| | __ge__(self, value, /)| Return self>=value.| | __getattribute__(self, name, /)| Return getattr(self, name).| | __getnewargs__(self, /)| | __gt__(self, value, /)| Return self>value.| | __hash__(self, /)| Return hash(self).| | __index__(self, /)| Return self converted to an integer, if self is suitable for use as an index into a list.| | __int__(self, /)| int(self)| | __invert__(self, /)| ~self| | __le__(self, value, /)| Return self<=value.| | __lshift__(self, value, /)| Return self<<value.| | __lt__(self, value, /)| Return self<value.| | __mod__(self, value, /)| Return self%value.| | __mul__(self, value, /)| Return self*value.| | __ne__(self, value, /)| Return self!=value.| | __neg__(self, /)| -self| | __or__(self, value, /)| Return self|value.| | __pos__(self, /)| +self| | __pow__(self, value, mod=None, /)| Return pow(self, value, mod).| | __radd__(self, value, /)| Return value+self.| | __rand__(self, value, /)| Return value&self.| | __rdivmod__(self, value, /)| Return divmod(value, self).| | __repr__(self, /)| Return repr(self).| | __rfloordiv__(self, value, /)| Return value//self.| | __rlshift__(self, value, /)| Return value<<self.| | __rmod__(self, value, /)| Return value%self.| | __rmul__(self, value, /)| Return value*self.| | __ror__(self, value, /)| Return value|self.| | __round__(...)| Rounding an Integral returns itself.| | Rounding with an ndigits argument also returns an integer.| | __rpow__(self, value, mod=None, /)| Return pow(value, self, mod).| | __rrshift__(self, value, /)| Return value>>self.| | __rshift__(self, value, /)| Return self>>value.| | __rsub__(self, value, /)| Return value-self.| | __rtruediv__(self, value, /)| Return value/self.| | __rxor__(self, value, /)| Return value^self.| | __sizeof__(self, /)| Returns size in memory, in bytes.| | __sub__(self, value, /)| Return self-value.| | __truediv__(self, value, /)| Return self/value.| | __trunc__(...)| Truncating an Integral returns itself.| | __xor__(self, value, /)| Return self^value.| | as_integer_ratio(self, /)| Return integer ratio.| | Return a pair of integers, whose ratio is exactly equal to the original int| and with a positive denominator.| | >>> (10).as_integer_ratio()| (10, 1)| >>> (-10).as_integer_ratio()| (-10, 1)| >>> (0).as_integer_ratio()| (0, 1)| | bit_count(self, /)| Number of ones in the binary representation of the absolute value of self.| | Also known as the population count.| | >>> bin(13)| '0b1101'| >>> (13).bit_count()| 3| | bit_length(self, /)| Number of bits necessary to represent self in binary.| | >>> bin(37)| '0b100101'| >>> (37).bit_length()| 6| | conjugate(...)| Returns self, the complex conjugate of any int.| | to_bytes(self, /, length=1, byteorder='big', *, signed=False)| Return an array of bytes representing an integer.| | length| Length of bytes object to use. An OverflowError is raised if the| integer is not representable with the given number of bytes. Default| is length 1.| byteorder| The byte order used to represent the integer. If byteorder is 'big',| the most significant byte is at the beginning of the byte array. If| byteorder is 'little', the most significant byte is at the end of the| byte array. To request the native byte order of the host system, use| `sys.byteorder' as the byte order value. Default is to use 'big'.| signed| Determines whether two's complement is used to represent the integer.| If signed is False and a negative integer is given, an OverflowError| is raised.| | ----------------------------------------------------------------------| Class methods defined here:| | from_bytes(bytes, byteorder='big', *, signed=False) from builtins.type| Return the integer represented by the given array of bytes.| | bytes| Holds the array of bytes to convert. The argument must either| support the buffer protocol or be an iterable object producing bytes.| Bytes and bytearray are examples of built-in objects that support the| buffer protocol.| byteorder| The byte order used to represent the integer. If byteorder is 'big',| the most significant byte is at the beginning of the byte array. If| byteorder is 'little', the most significant byte is at the end of the| byte array. To request the native byte order of the host system, use| `sys.byteorder' as the byte order value. Default is to use 'big'.| signed| Indicates whether two's complement is used to represent the integer.| | ----------------------------------------------------------------------| Static methods defined here:| | __new__(*args, **kwargs) from builtins.type| Create and return a new object. See help(type) for accurate signature.| | ----------------------------------------------------------------------| Data descriptors defined here:| | denominator| the denominator of a rational number in lowest terms| | imag| the imaginary part of a complex number| | numerator| the numerator of a rational number in lowest terms| | real| the real part of a complex number
我的天呐,好多啊。大家看到了吧,上述结果说明了一件我们平时忽略的事情:
Python从内到外评估表达式。
首先它计算round(-2.01)的值,然后提供关于该表达式输出的帮助。
(事实证明Python对整数有很多要说!在我们稍后讨论Python中的对象,方法和属性之后,上面的帮助输出将更有意义。)
round是一个非常简单的函数,有一个简短的文档字符串。当处理更复杂,可配置的函数(如print)时,帮助功能更加突出。
如果下面的输出看起来难以理解,请不要担心…现在只是看看是否能从这个帮助中找到任何新信息。
help(print)
如果你在寻找的话,你可能会发现print函数可以接受一个叫做sep的参数,它描述了我们在打印其他参数时放在它们之间的内容。
定义函数
内置函数非常好用,很多情况下,需要定义自己的函数,以下是一个简单的例子。
def least_difference(a, b, c):diff1 = abs(a - b)diff2 = abs(b - c)diff3 = abs(a - c)return min(diff1, diff2, diff3)
咱们创建了一个名为least_difference的函数,它接受三个参数a、b和c。
函数定义以使用def关键字引入的标头开头。冒号后的缩进代码块在调用函数时运行。
return是与函数唯一相关的另一个关键字。
当Python遇到return语句时,它立即退出函数,并将右侧的值传递给调用上下文。
从源代码中清楚least_difference()的功能吗?如果我们不确定,我们可以在几个示例上尝试它:
print(least_difference(1, 10, 100),least_difference(1, 10, 10),least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?
)
以下是执行:
或者也许help()函数可以告诉我们一些关于它的信息。
help(least_difference)
可以看到帮助信息中展示的是刚才咱们定义的函数:
Python不足以智能地阅读我的代码并将其转化为优美的英文描述。然而,当我编写一个函数时,我可以在所谓的文档字符串中提供描述。当咱们添加了这个描述,就可以在帮助信息中被看到啦。
Docstrings是一种在程序代码中文档化函数、模块和类的方法。它是由开发者编写的字符串,用于描述代码的功能、输入参数、返回值等信息。这些文档字符串可以被Python解释器读取,并在交互式环境中使用help()
函数查看。同时,它们也可以被一些工具自动生成的文档或IDE使用,以提供代码的说明和提示。Docstrings一般放在函数、类或模块的开头,在三个引号之间编写。常见的Docstrings格式有多种,比如Google风格、reStructuredText风格和numpy风格等。
def least_difference(a, b, c):"""Return the smallest difference between any two numbersamong a, b and c.>>> least_difference(1, 5, -5)4"""diff1 = abs(a - b)diff2 = abs(b - c)diff3 = abs(a - c)return min(diff1, diff2, diff3)
docstring是一个用三引号括起来的字符串(可以跨多行),紧跟在函数的头部之后。当我们对一个函数调用help()时,它会显示出docstring。
help(least_difference)
备注:
文档字符串的最后两行是一个示例函数调用和结果。
(>>>是对Python交互式shell中使用的命令提示符的引用。)
Python不会运行示例调用-它只是为了读者的方便而存在。在函数的文档字符串中包含一个或多个示例调用的惯例远非普遍遵守,但它可以非常有效地帮助人们理解您的函数。
好的程序员会使用文档字符串,除非他们预计在使用后不久就会丢弃代码(这种情况很少见)。所以,你也应该开始编写文档字符串!
没有返回值的函数
如果我们在函数中没有包含return关键字会发生什么?
Python允许我们定义这样的函数。调用它们的结果是特殊的值None。
(这类似于其他语言中的“null”概念。)
没有return语句,least_difference函数就毫无意义,但是具有副作用的函数可能在不返回任何内容的情况下执行一些有用的操作。
我们已经看到了两个例子:print()和help()不返回任何内容。我们只是为了它们的执行作用(在屏幕上输出一些文本)而调用它们。其他有用的仅靠执行作用的例子包括写入文件或修改输入。
mystery = print()
print(mystery)
默认参数
当我们调用help(print)时,我们发现print函数有几个可选参数。例如,我们可以为sep指定一个值,在我们打印的参数之间放入一些特殊的字符串:
print(1, 2, 3, sep=' < ')
但是如果我们不指定一个值,sep会被视为具有默认值' '(一个空格)。
print(1, 2, 3)
给我们定义的函数添加具有默认值的可选参数其实非常简单:
def greet(who="Colin"):print("Hello,", who)greet()
greet(who="Kaggle")
# (In this case, we don't need to specify the name of the argument, because it's unambiguous.)
greet("world")
函数调用
这里有一些很强大的东西,尽管一开始可能感觉很抽象。你可以将函数作为参数传递给其他函数。一些示例可能会更加清楚:
def mult_by_five(x):return 5 * xdef call(fn, arg):"""Call fn on arg"""return fn(arg)def squared_call(fn, arg):"""Call fn on the result of calling fn on arg"""return fn(fn(arg))print(call(mult_by_five, 1),squared_call(mult_by_five, 1), sep='\n', # '\n' is the newline character - it starts a new line
)
可以操作其他函数的函数被称为“高阶函数”。你可能不会立即编写自己的高阶函数。但Python内置了一些高阶函数,你可能会发现调用它们很有用。
下面是一个有趣的例子,使用了max函数。
默认情况下,max返回其参数中的最大值。但是如果我们使用可选的key参数传入一个函数,它将返回使key(x)(也被称为'argmax')最大化的参数x。
def mod_5(x):"""Return the remainder of x after dividing by 5"""return x % 5print('Which number is biggest?',max(100, 51, 14),'Which number is the biggest modulo 5?',max(100, 51, 14, key=mod_5),sep='\n',
)
轮到你啦
函数在Python编程中打开了一个全新的世界。
相关文章:

政安晨:示例演绎Python的函数与获取帮助的方法
调用函数和定义我们自己的函数,并使用Python内置的文档,是成为一位Pythoner的开始。 通过我的上篇文章,相信您已经看过并使用了print和abs等函数。但是Python还有许多其他函数,并且定义自己的函数是Python编程的重要部分。 在本…...

88 docker 环境下面 前端A连到后端B + 前端B连到后端A
前言 呵呵 最近出现了这样的一个问题, 我们有多个前端服务, 分别连接了对应的后端服务, 前端A -> 后端A, 前端B -> 后端B 但是 最近的时候 却会出现一种情况就是, 有些时候 前端A 连接到了 后端B, 前端B 连接到了 后端A 我们 前端服务使用 nginx 提供前端 html, js…...
k8s学习-Service Account和RBAC授权
1.1 ServiceAccount 介绍 首先Kubernetes中账户区分为:User Accounts(用户账户) 和 Service Accounts(服务账户) 两种,它们的设计及用途如下: UserAccount是给kubernetes集群外部用户使用的&am…...
SpringMVC-响应数据
一、引子 我们在上一篇文章SpringMVC-组件解析里介绍了SpringMVC框架执行一个请求的过程,并演示了快速使用Controller承接请求。本篇我们将深入介绍SpringMVC执行请求时,如何响应客户端。 二、响应类型 SpringMVC的数据响应方式主要分为两类ÿ…...

数学建模:数据相关性分析(Pearson和 Spearman相关系数)含python实现
相关性分析是一种用于衡量两个或多个变量之间关系密切程度的方法。相关性分析通常用于探索变量之间的关系,以及预测一个变量如何随着另一个变量的变化而变化。在数学建模中,这是常用的数据分析手段。 相关性分析的结果通常用相关系数来表示ÿ…...

使用pandas将excel转成json格式
1.Excel数据 2.我们想要的JSON格式 {"0": {"raw_data1": "Sam","raw_data2": "Wong","raw_data3": "Good","layer": "12v1"},"1": {"raw_data1": "Lucy…...

双向链表的插入、删除、按位置增删改查、栈和队列区别、什么是内存泄漏
2024年2月4日 1.请编程实现双向链表的头插,头删、尾插、尾删 头文件: #ifndef __HEAD_H__ #define __HEAD_H__ #include<stdio.h> #include<stdlib.h> #include<string.h> typedef int datatype; enum{FALSE-1,SUCCSE}; typedef str…...

Linux 驱动开发基础知识——总线设备驱动模型(七)
个人名片: 🦁作者简介:学生 🐯个人主页:妄北y 🐧个人QQ:2061314755 🐻个人邮箱:2061314755qq.com 🦉个人WeChat:Vir2021GKBS 🐼本文由…...
RTthread线程间通信(邮箱,消息队列,信号/软件中断)---03信号(软件中断)源码分析
信号 实际使用看这一个 #if defined(RT_USING_SIGNALS)rt_sigset_t sig_pending; /**< the pending signals 记录来了的信号 */rt_sigset_t sig_mask; /**< the mask bits of signal 记录屏蔽的信号 */rt_sigh…...

老版本labelme如何不保存imagedata
我的版本是3.16,默认英文且不带取消保存imagedata的选项。 最简单粗暴的方法就是在json文件保存时把传递过来的imagedata数据设定为None,方法如下: 找到labelme的源文件,例如:D:\conda\envs\deeplab\Lib\site-packages…...

vscode 如何修改c/c++格式化风格,大括号不换行
在Visual Studio Code(VSCode)中,若要修改C代码格式化的风格以实现大括号不换行,通常会借助于插件C/C扩展中的ClangFormat配置。以下是具体的步骤: 确保已安装了C/C扩展: 打开VSCode的扩展市场(…...

IP协议(2) 和 数据链路层协议基础
IP协议续 1.路由选择 在复杂的网络结构中,我们需要找到一个通往终点的路线,这就是路由选择 举个例子:我们在没有手机导航之前,想去一个地方得是到一个地方问一下路的方式最终找到目的地 路由的过程,其实就是样子问路的过程 1.当IP数据包到达路由器的时候,会查看目的IP 2.路由器…...
Flink-1.18.1环境搭建
下载 下载flink安装包 Index of /dist/flink/flink-1.18.1 下载flink-cdc安装包 Release Release 3.0.0 ververica/flink-cdc-connectors GitHub 安装 添加环境变量 vi ~/.bash_profile export FLINK_HOME=/home/postgres/flink/flink-1.18.1 export PATH=$PATH:$FL…...
deepin20.9安装及配置
安装deepin20.9很简单,刻录u盘 安装 一路next apt install nginx global vim-nox debian11 使用apt安装php, 使php多版本共存_debain11 php5-CSDN博客 vim LeaderF安装问题 - 知乎 debian10安装vue环境, 包括安装node.js-CSDN博客 debian安装vue3 nodejs20-CSD…...

2-2 动手学深度学习v2-损失函数-笔记
损失函数,用来衡量预测值和真实值之间的区别。是机器学习里面一个非常重要的概念。 三个常用的损失函数 L2 loss、L1 loss、Huber’s Robust loss 均方损失 L2 Loss l ( y , y ′ ) 1 2 ( y − y ′ ) 2 l(y,y^{\prime})\frac{1}{2}(y-y^{\prime})^{2} l(y,y′)21…...
非springboot 使用aop 切面
在非Spring Boot应用中使用AOP(Aspect Oriented Programming,面向切面编程)的代码实现需要依赖Spring AOP库。由于Spring AOP库并不直接支持非Spring应用,你需要将Spring AOP库作为依赖项添加到项目中,并使用Spring AO…...
MongoDB 字段中数据类型不一致序列化异常排查与处理
MongoDB 字段中数据类型不一致序列化异常排查与处理 背景如下,因为项目迁移愿意,一个使用Mongodb的业务拥有C#和Java两组Api。Java Api开发和测试都很顺利。上线一段时间后,客服反馈记录都不见了。查看数据库发现,时间字段拥有两…...
网络安全简介
网络安全: 网络安全攻击分为被动攻击和主动攻击。 1. 被动攻击:是指攻击者从网络上窃取了他人的通信内容,通常把这类的攻击称为截获,被动攻击只要有2种形式:消息内容泄漏攻击和流量分析攻击。由于攻击者没…...

【Docker】.NET Core 6.0 webapi 发布上传到Docker Desktop并启动运行访问,接口返回数据乱码解决方法
欢迎来到《小5讲堂》,大家好,我是全栈小5。 这是《Docker容器》系列文章,每篇文章将以博主理解的角度展开讲解, 特别是针对知识点的概念进行叙说,大部分文章将会对这些概念进行实际例子验证,以此达到加深对…...

【Android Gradle 插件】自定义 Gradle 插件模块 ⑤ ( 完整总结 )
一、创建自定义插件类型模块 ( Java or Kotlin Library ) 选择 " 菜单栏 / New / New Module… " 选项 , 在 " Create New Module " 对话框中 , 选择 创建 " Java or Kotlin Library " 类型的依赖库 ; 二、手动导入相关依赖 ( Java | Groovy | …...

Flask RESTful 示例
目录 1. 环境准备2. 安装依赖3. 修改main.py4. 运行应用5. API使用示例获取所有任务获取单个任务创建新任务更新任务删除任务 中文乱码问题: 下面创建一个简单的Flask RESTful API示例。首先,我们需要创建环境,安装必要的依赖,然后…...

简易版抽奖活动的设计技术方案
1.前言 本技术方案旨在设计一套完整且可靠的抽奖活动逻辑,确保抽奖活动能够公平、公正、公开地进行,同时满足高并发访问、数据安全存储与高效处理等需求,为用户提供流畅的抽奖体验,助力业务顺利开展。本方案将涵盖抽奖活动的整体架构设计、核心流程逻辑、关键功能实现以及…...

dedecms 织梦自定义表单留言增加ajax验证码功能
增加ajax功能模块,用户不点击提交按钮,只要输入框失去焦点,就会提前提示验证码是否正确。 一,模板上增加验证码 <input name"vdcode"id"vdcode" placeholder"请输入验证码" type"text&quo…...
【android bluetooth 框架分析 04】【bt-framework 层详解 1】【BluetoothProperties介绍】
1. BluetoothProperties介绍 libsysprop/srcs/android/sysprop/BluetoothProperties.sysprop BluetoothProperties.sysprop 是 Android AOSP 中的一种 系统属性定义文件(System Property Definition File),用于声明和管理 Bluetooth 模块相…...

令牌桶 滑动窗口->限流 分布式信号量->限并发的原理 lua脚本分析介绍
文章目录 前言限流限制并发的实际理解限流令牌桶代码实现结果分析令牌桶lua的模拟实现原理总结: 滑动窗口代码实现结果分析lua脚本原理解析 限并发分布式信号量代码实现结果分析lua脚本实现原理 双注解去实现限流 并发结果分析: 实际业务去理解体会统一注…...
Java多线程实现之Thread类深度解析
Java多线程实现之Thread类深度解析 一、多线程基础概念1.1 什么是线程1.2 多线程的优势1.3 Java多线程模型 二、Thread类的基本结构与构造函数2.1 Thread类的继承关系2.2 构造函数 三、创建和启动线程3.1 继承Thread类创建线程3.2 实现Runnable接口创建线程 四、Thread类的核心…...

以光量子为例,详解量子获取方式
光量子技术获取量子比特可在室温下进行。该方式有望通过与名为硅光子学(silicon photonics)的光波导(optical waveguide)芯片制造技术和光纤等光通信技术相结合来实现量子计算机。量子力学中,光既是波又是粒子。光子本…...

保姆级教程:在无网络无显卡的Windows电脑的vscode本地部署deepseek
文章目录 1 前言2 部署流程2.1 准备工作2.2 Ollama2.2.1 使用有网络的电脑下载Ollama2.2.2 安装Ollama(有网络的电脑)2.2.3 安装Ollama(无网络的电脑)2.2.4 安装验证2.2.5 修改大模型安装位置2.2.6 下载Deepseek模型 2.3 将deepse…...
音视频——I2S 协议详解
I2S 协议详解 I2S (Inter-IC Sound) 协议是一种串行总线协议,专门用于在数字音频设备之间传输数字音频数据。它由飞利浦(Philips)公司开发,以其简单、高效和广泛的兼容性而闻名。 1. 信号线 I2S 协议通常使用三根或四根信号线&a…...
Android屏幕刷新率与FPS(Frames Per Second) 120hz
Android屏幕刷新率与FPS(Frames Per Second) 120hz 屏幕刷新率是屏幕每秒钟刷新显示内容的次数,单位是赫兹(Hz)。 60Hz 屏幕:每秒刷新 60 次,每次刷新间隔约 16.67ms 90Hz 屏幕:每秒刷新 90 次,…...