当前位置:   article > 正文

政安晨:示例演绎Python的函数与获取帮助的方法

政安晨:示例演绎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))

刚刚显示的完整的详细信息见下面:

  1. Help on int object:
  2. class int(object)
  3. | int([x]) -> integer
  4. | int(x, base=10) -> integer
  5. |
  6. | Convert a number or string to an integer, or return 0 if no arguments
  7. | are given. If x is a number, return x.__int__(). For floating point
  8. | numbers, this truncates towards zero.
  9. |
  10. | If x is not a number or if base is given, then x must be a string,
  11. | bytes, or bytearray instance representing an integer literal in the
  12. | given base. The literal can be preceded by '+' or '-' and be surrounded
  13. | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
  14. | Base 0 means to interpret the base from the string as an integer literal.
  15. | >>> int('0b100', base=0)
  16. | 4
  17. |
  18. | Built-in subclasses:
  19. | bool
  20. |
  21. | Methods defined here:
  22. |
  23. | __abs__(self, /)
  24. | abs(self)
  25. |
  26. | __add__(self, value, /)
  27. | Return self+value.
  28. |
  29. | __and__(self, value, /)
  30. | Return self&value.
  31. |
  32. | __bool__(self, /)
  33. | True if self else False
  34. |
  35. | __ceil__(...)
  36. | Ceiling of an Integral returns itself.
  37. |
  38. | __divmod__(self, value, /)
  39. | Return divmod(self, value).
  40. |
  41. | __eq__(self, value, /)
  42. | Return self==value.
  43. |
  44. | __float__(self, /)
  45. | float(self)
  46. |
  47. | __floor__(...)
  48. | Flooring an Integral returns itself.
  49. |
  50. | __floordiv__(self, value, /)
  51. | Return self//value.
  52. |
  53. | __format__(self, format_spec, /)
  54. | Default object formatter.
  55. |
  56. | __ge__(self, value, /)
  57. | Return self>=value.
  58. |
  59. | __getattribute__(self, name, /)
  60. | Return getattr(self, name).
  61. |
  62. | __getnewargs__(self, /)
  63. |
  64. | __gt__(self, value, /)
  65. | Return self>value.
  66. |
  67. | __hash__(self, /)
  68. | Return hash(self).
  69. |
  70. | __index__(self, /)
  71. | Return self converted to an integer, if self is suitable for use as an index into a list.
  72. |
  73. | __int__(self, /)
  74. | int(self)
  75. |
  76. | __invert__(self, /)
  77. | ~self
  78. |
  79. | __le__(self, value, /)
  80. | Return self<=value.
  81. |
  82. | __lshift__(self, value, /)
  83. | Return self<<value.
  84. |
  85. | __lt__(self, value, /)
  86. | Return self<value.
  87. |
  88. | __mod__(self, value, /)
  89. | Return self%value.
  90. |
  91. | __mul__(self, value, /)
  92. | Return self*value.
  93. |
  94. | __ne__(self, value, /)
  95. | Return self!=value.
  96. |
  97. | __neg__(self, /)
  98. | -self
  99. |
  100. | __or__(self, value, /)
  101. | Return self|value.
  102. |
  103. | __pos__(self, /)
  104. | +self
  105. |
  106. | __pow__(self, value, mod=None, /)
  107. | Return pow(self, value, mod).
  108. |
  109. | __radd__(self, value, /)
  110. | Return value+self.
  111. |
  112. | __rand__(self, value, /)
  113. | Return value&self.
  114. |
  115. | __rdivmod__(self, value, /)
  116. | Return divmod(value, self).
  117. |
  118. | __repr__(self, /)
  119. | Return repr(self).
  120. |
  121. | __rfloordiv__(self, value, /)
  122. | Return value//self.
  123. |
  124. | __rlshift__(self, value, /)
  125. | Return value<<self.
  126. |
  127. | __rmod__(self, value, /)
  128. | Return value%self.
  129. |
  130. | __rmul__(self, value, /)
  131. | Return value*self.
  132. |
  133. | __ror__(self, value, /)
  134. | Return value|self.
  135. |
  136. | __round__(...)
  137. | Rounding an Integral returns itself.
  138. |
  139. | Rounding with an ndigits argument also returns an integer.
  140. |
  141. | __rpow__(self, value, mod=None, /)
  142. | Return pow(value, self, mod).
  143. |
  144. | __rrshift__(self, value, /)
  145. | Return value>>self.
  146. |
  147. | __rshift__(self, value, /)
  148. | Return self>>value.
  149. |
  150. | __rsub__(self, value, /)
  151. | Return value-self.
  152. |
  153. | __rtruediv__(self, value, /)
  154. | Return value/self.
  155. |
  156. | __rxor__(self, value, /)
  157. | Return value^self.
  158. |
  159. | __sizeof__(self, /)
  160. | Returns size in memory, in bytes.
  161. |
  162. | __sub__(self, value, /)
  163. | Return self-value.
  164. |
  165. | __truediv__(self, value, /)
  166. | Return self/value.
  167. |
  168. | __trunc__(...)
  169. | Truncating an Integral returns itself.
  170. |
  171. | __xor__(self, value, /)
  172. | Return self^value.
  173. |
  174. | as_integer_ratio(self, /)
  175. | Return integer ratio.
  176. |
  177. | Return a pair of integers, whose ratio is exactly equal to the original int
  178. | and with a positive denominator.
  179. |
  180. | >>> (10).as_integer_ratio()
  181. | (10, 1)
  182. | >>> (-10).as_integer_ratio()
  183. | (-10, 1)
  184. | >>> (0).as_integer_ratio()
  185. | (0, 1)
  186. |
  187. | bit_count(self, /)
  188. | Number of ones in the binary representation of the absolute value of self.
  189. |
  190. | Also known as the population count.
  191. |
  192. | >>> bin(13)
  193. | '0b1101'
  194. | >>> (13).bit_count()
  195. | 3
  196. |
  197. | bit_length(self, /)
  198. | Number of bits necessary to represent self in binary.
  199. |
  200. | >>> bin(37)
  201. | '0b100101'
  202. | >>> (37).bit_length()
  203. | 6
  204. |
  205. | conjugate(...)
  206. | Returns self, the complex conjugate of any int.
  207. |
  208. | to_bytes(self, /, length=1, byteorder='big', *, signed=False)
  209. | Return an array of bytes representing an integer.
  210. |
  211. | length
  212. | Length of bytes object to use. An OverflowError is raised if the
  213. | integer is not representable with the given number of bytes. Default
  214. | is length 1.
  215. | byteorder
  216. | The byte order used to represent the integer. If byteorder is 'big',
  217. | the most significant byte is at the beginning of the byte array. If
  218. | byteorder is 'little', the most significant byte is at the end of the
  219. | byte array. To request the native byte order of the host system, use
  220. | `sys.byteorder' as the byte order value. Default is to use 'big'.
  221. | signed
  222. | Determines whether two's complement is used to represent the integer.
  223. | If signed is False and a negative integer is given, an OverflowError
  224. | is raised.
  225. |
  226. | ----------------------------------------------------------------------
  227. | Class methods defined here:
  228. |
  229. | from_bytes(bytes, byteorder='big', *, signed=False) from builtins.type
  230. | Return the integer represented by the given array of bytes.
  231. |
  232. | bytes
  233. | Holds the array of bytes to convert. The argument must either
  234. | support the buffer protocol or be an iterable object producing bytes.
  235. | Bytes and bytearray are examples of built-in objects that support the
  236. | buffer protocol.
  237. | byteorder
  238. | The byte order used to represent the integer. If byteorder is 'big',
  239. | the most significant byte is at the beginning of the byte array. If
  240. | byteorder is 'little', the most significant byte is at the end of the
  241. | byte array. To request the native byte order of the host system, use
  242. | `sys.byteorder' as the byte order value. Default is to use 'big'.
  243. | signed
  244. | Indicates whether two's complement is used to represent the integer.
  245. |
  246. | ----------------------------------------------------------------------
  247. | Static methods defined here:
  248. |
  249. | __new__(*args, **kwargs) from builtins.type
  250. | Create and return a new object. See help(type) for accurate signature.
  251. |
  252. | ----------------------------------------------------------------------
  253. | Data descriptors defined here:
  254. |
  255. | denominator
  256. | the denominator of a rational number in lowest terms
  257. |
  258. | imag
  259. | the imaginary part of a complex number
  260. |
  261. | numerator
  262. | the numerator of a rational number in lowest terms
  263. |
  264. | real
  265. | the real part of a complex number

我的天呐,好多啊。大家看到了吧,上述结果说明了一件我们平时忽略的事情:

Python从内到外评估表达式。

首先它计算round(-2.01)的值,然后提供关于该表达式输出的帮助。

事实证明Python对整数有很多要说!在我们稍后讨论Python中的对象,方法和属性之后,上面的帮助输出将更有意义。

round是一个非常简单的函数,有一个简短的文档字符串。当处理更复杂,可配置的函数(如print)时,帮助功能更加突出。

如果下面的输出看起来难以理解,请不要担心…现在只是看看是否能从这个帮助中找到任何新信息。

help(print)

如果你在寻找的话,你可能会发现print函数可以接受一个叫做sep的参数,它描述了我们在打印其他参数时放在它们之间的内容。

定义函数

内置函数非常好用,很多情况下,需要定义自己的函数,以下是一个简单的例子。

  1. def least_difference(a, b, c):
  2. diff1 = abs(a - b)
  3. diff2 = abs(b - c)
  4. diff3 = abs(a - c)
  5. return min(diff1, diff2, diff3)

咱们创建了一个名为least_difference的函数,它接受三个参数a、b和c。

函数定义以使用def关键字引入的标头开头。冒号后的缩进代码块在调用函数时运行。

return是与函数唯一相关的另一个关键字。

当Python遇到return语句时,它立即退出函数,并将右侧的值传递给调用上下文。

从源代码中清楚least_difference()的功能吗?如果我们不确定,我们可以在几个示例上尝试它:

  1. print(
  2. least_difference(1, 10, 100),
  3. least_difference(1, 10, 10),
  4. least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?
  5. )

以下是执行:

或者也许help()函数可以告诉我们一些关于它的信息。

help(least_difference)

可以看到帮助信息中展示的是刚才咱们定义的函数:

        Python不足以智能地阅读我的代码并将其转化为优美的英文描述。然而,当我编写一个函数时,我可以在所谓的文档字符串中提供描述。当咱们添加了这个描述,就可以在帮助信息中被看到啦。

        Docstrings是一种在程序代码中文档化函数、模块和类的方法。它是由开发者编写的字符串,用于描述代码的功能、输入参数、返回值等信息。这些文档字符串可以被Python解释器读取,并在交互式环境中使用help()函数查看。同时,它们也可以被一些工具自动生成的文档或IDE使用,以提供代码的说明和提示。Docstrings一般放在函数、类或模块的开头,在三个引号之间编写。常见的Docstrings格式有多种,比如Google风格、reStructuredText风格和numpy风格等。

  1. def least_difference(a, b, c):
  2. """Return the smallest difference between any two numbers
  3. among a, b and c.
  4. >>> least_difference(1, 5, -5)
  5. 4
  6. """
  7. diff1 = abs(a - b)
  8. diff2 = abs(b - c)
  9. diff3 = abs(a - c)
  10. return min(diff1, diff2, diff3)

docstring是一个用三引号括起来的字符串(可以跨多行),紧跟在函数的头部之后。当我们对一个函数调用help()时,它会显示出docstring。

help(least_difference)

备注:

文档字符串的最后两行是一个示例函数调用和结果。

(>>>是对Python交互式shell中使用的命令提示符的引用。)

Python不会运行示例调用-它只是为了读者的方便而存在。在函数的文档字符串中包含一个或多个示例调用的惯例远非普遍遵守,但它可以非常有效地帮助人们理解您的函数。

好的程序员会使用文档字符串,除非他们预计在使用后不久就会丢弃代码(这种情况很少见)。所以,你也应该开始编写文档字符串!

没有返回值的函数

如果我们在函数中没有包含return关键字会发生什么?

Python允许我们定义这样的函数。调用它们的结果是特殊的值None。

(这类似于其他语言中的“null”概念。)

没有return语句,least_difference函数就毫无意义,但是具有副作用的函数可能在不返回任何内容的情况下执行一些有用的操作。

我们已经看到了两个例子:print()和help()不返回任何内容。我们只是为了它们的执行作用(在屏幕上输出一些文本)而调用它们。其他有用的仅靠执行作用的例子包括写入文件或修改输入。

  1. mystery = print()
  2. print(mystery)

默认参数

当我们调用help(print)时,我们发现print函数有几个可选参数。例如,我们可以为sep指定一个值,在我们打印的参数之间放入一些特殊的字符串:

print(1, 2, 3, sep=' < ')

但是如果我们不指定一个值,sep会被视为具有默认值' '(一个空格)。

print(1, 2, 3)

给我们定义的函数添加具有默认值的可选参数其实非常简单:

  1. def greet(who="Colin"):
  2. print("Hello,", who)
  3. greet()
  4. greet(who="Kaggle")
  5. # (In this case, we don't need to specify the name of the argument, because it's unambiguous.)
  6. greet("world")

函数调用

这里有一些很强大的东西,尽管一开始可能感觉很抽象。你可以将函数作为参数传递给其他函数。一些示例可能会更加清楚:

  1. def mult_by_five(x):
  2. return 5 * x
  3. def call(fn, arg):
  4. """Call fn on arg"""
  5. return fn(arg)
  6. def squared_call(fn, arg):
  7. """Call fn on the result of calling fn on arg"""
  8. return fn(fn(arg))
  9. print(
  10. call(mult_by_five, 1),
  11. squared_call(mult_by_five, 1),
  12. sep='\n', # '\n' is the newline character - it starts a new line
  13. )

可以操作其他函数的函数被称为“高阶函数”。你可能不会立即编写自己的高阶函数。但Python内置了一些高阶函数,你可能会发现调用它们很有用。

下面是一个有趣的例子,使用了max函数。

默认情况下,max返回其参数中的最大值。但是如果我们使用可选的key参数传入一个函数,它将返回使key(x)(也被称为'argmax')最大化的参数x。

  1. def mod_5(x):
  2. """Return the remainder of x after dividing by 5"""
  3. return x % 5
  4. print(
  5. 'Which number is biggest?',
  6. max(100, 51, 14),
  7. 'Which number is the biggest modulo 5?',
  8. max(100, 51, 14, key=mod_5),
  9. sep='\n',
  10. )

轮到你啦

函数在Python编程中打开了一个全新的世界。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/124230
推荐阅读
相关标签
  

闽ICP备14008679号