Flashield's Blog

Just For My Daily Diary

Flashield's Blog

Just For My Daily Diary

functions-and-getting-help【函数和获取帮助】

You've already seen and used functions such as print and abs. But Python has many more functions, and defining your own functions is a big part of python programming.

In this lesson, you will learn more about using and defining functions.

您已经看到并使用了诸如printabs之类的函数。但是Python具有更多功能,定义自己的函数是Python编程的重要组成部分。

在本课程中,您将了解有关使用和定义函数的更多信息。

Getting Help

You saw the abs function in the previous tutorial, but what if you've forgotten what it does?

The help() function is possibly the most important Python function you can learn. If you can remember how to use help(), you hold the key to understanding most other functions.

Here is an example:

获取帮助

您在上一个教程中看到了abs函数,但是如果您忘记了它的作用怎么办?

help()函数可能是您可以学习的最重要的 Python 函数。 如果您能记住如何使用help(),那么您就掌握了理解大多数其他函数的关键。

这是一个例子:

help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.

    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.

help() displays two things:

  1. the header of that function round(number, ndigits=None). In this case, this tells us that round() takes an argument we can describe as number. Additionally, we can optionally give a separate argument which could be described as ndigits.
  2. A brief English description of what the function does.

help() 显示两件事:

  1. 该函数round(number, ndigits=None)的标头。 在本例中,这告诉我们round()接受一个我们可以描述为number的参数。 此外,我们可以选择给出一个单独的参数,可以将其描述为ndigits
  2. 该函数功能的简短英文描述。

Common pitfall: when you're looking up a function, remember to pass in the name of the function itself, and not the result of calling that function.

What happens if we invoke help on a call to the function round()? Unhide the output of the cell below to see.

常见陷阱: 当您查找函数时,请记住传递函数本身的名称,而不是调用该函数的结果。

如果我们在调用函数round()时调用帮助,会发生什么? 取消隐藏下面单元格的输出即可查看。

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<>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, byteorder, *, 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.
 |      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.
 |      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, *, 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.
 |      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 evaluates an expression like this from the inside out. First it calculates the value of round(-2.01), then it provides help on the output of that expression.

(And it turns out to have a lot to say about integers! After we talk later about objects, methods, and attributes in Python, the help output above will make more sense.)

round is a very simple function with a short docstring. help shines even more when dealing with more complex, configurable functions like print. Don't worry if the following output looks inscrutable... for now, just see if you can pick anything new out from this help.

Python 从内到外对这样的表达式求值。 首先,它计算round(-2.01)的值,然后提供有关该表达式输出的帮助。

(事实证明,关于整数有很多话要说!稍后我们讨论 Python 中的对象、方法和属性后,上面的帮助输出会更有意义。)

round是一个非常简单的函数,文档字符串很短。 在处理更复杂的、可配置的函数(如print)时,help更加闪耀。 如果以下输出看起来难以理解,请不要担心......现在,只需看看您是否可以从此帮助中挑选出任何新内容。

help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

If you were looking for it, you might learn that print can take an argument called sep, and that this describes what we put between all the other arguments when we print them.

如果您正在寻找它,您可能会了解到 print 可以接受一个名为sep的参数,并且这描述了我们在打印它们时在所有其他参数之间放置的内容。

Defining functions

Builtin functions are great, but we can only get so far with them before we need to start defining our own functions. Below is a simple example.

定义函数

内置函数很棒,但在我们需要开始定义自己的函数之前,我们只能了解它们这么多。 下面是一个简单的例子。

def least_difference(a, b, c):
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3)

This creates a function called least_difference, which takes three arguments, a, b, and c.

Functions start with a header introduced by the def keyword. The indented block of code following the : is run when the function is called.

return is another keyword uniquely associated with functions. When Python encounters a return statement, it exits the function immediately, and passes the value on the right hand side to the calling context.

Is it clear what least_difference() does from the source code? If we're not sure, we can always try it out on a few examples:

这将创建一个名为least_difference的函数,它接受三个参数:abc

函数以由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?
)
9 0 1

Or maybe the help() function can tell us something about it.

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

help(least_difference)
Help on function least_difference in module __main__:

least_difference(a, b, c)

Python isn't smart enough to read my code and turn it into a nice English description. However, when I write a function, I can provide a description in what's called the docstring.

Docstrings

Python 不够聪明,无法阅读我的代码并将其转化为漂亮的英文描述。 但是,当我编写函数时,我可以在所谓的 docstring 中提供描述。

文档字符串

def least_difference(a, b, c):
    """Return the smallest difference between any two numbers
    among 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)

The docstring is a triple-quoted string (which may span multiple lines) that comes immediately after the header of a function. When we call help() on a function, it shows the docstring.

文档字符串是一个三引号字符串(可能跨越多行),紧跟在函数标题之后。 当我们在函数上调用help()时,它会显示文档字符串。

help(least_difference)
Help on function least_difference in module __main__:

least_difference(a, b, c)
    Return the smallest difference between any two numbers
    among a, b and c.

    >>> least_difference(1, 5, -5)
    4

Aside:
The last two lines of the docstring are an example function call and result. (The >>> is a reference to the command prompt used in Python interactive shells.) Python doesn't run the example call - it's just there for the benefit of the reader. The convention of including 1 or more example calls in a function's docstring is far from universally observed, but it can be very effective at helping someone understand your function. For a real-world example, see this docstring for the numpy function np.eye.

旁白:
文档字符串的最后两行是示例函数调用和结果。 (“>>>”是对 Python 交互式 shell 中使用的命令提示符的引用。)Python 不运行示例调用 - 它只是为了读者的利益而存在。 在函数的文档字符串中包含 1 个或多个示例调用的约定远未得到普遍遵守,但它可以非常有效地帮助人们理解您的函数。 有关实际示例,请参阅 numpy 函数 np.eye 的文档字符串

Good programmers use docstrings unless they expect to throw away the code soon after it's used (which is rare). So, you should start writing docstrings, too!

优秀的程序员会使用文档字符串,除非他们希望在使用代码后立即丢弃代码(这种情况很少见)。 所以,你也应该开始编写文档字符串!

Functions that don't return

What would happen if we didn't include the return keyword in our function?

如果我们的函数中不包含return关键字会发生什么?

def least_difference(a, b, c):
    """Return the smallest difference between any two numbers
    among a, b and c.
    """
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    min(diff1, diff2, diff3)

print(
    least_difference(1, 10, 100),
    least_difference(1, 10, 10),
    least_difference(5, 6, 7),
)
None None None

Python allows us to define such functions. The result of calling them is the special value None. (This is similar to the concept of "null" in other languages.)

Without a return statement, least_difference is completely pointless, but a function with side effects may do something useful without returning anything. We've already seen two examples of this: print() and help() don't return anything. We only call them for their side effects (putting some text on the screen). Other examples of useful side effects include writing to a file, or modifying an input.

Python 允许我们定义这样的函数。 调用它们的结果是特殊值None。 (这类似于其他语言中null的概念。)

如果没有 return 语句,least_difference 是完全没有意义的,但是具有副作用的函数可能会在不返回任何内容的情况下做一些有用的事情。 我们已经看到了两个这样的例子:print()help()不返回任何内容。 我们只是因为它们的副作用(在屏幕上放置一些文本)而调用它们。 有用的副作用的其他示例包括写入文件或修改输入。

mystery = print()
print(mystery)
None

Default arguments

When we called help(print), we saw that the print function has several optional arguments. For example, we can specify a value for sep to put some special string in between our printed arguments:

默认参数

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

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

But if we don't specify a value, sep is treated as having a default value of ' ' (a single space).

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

print(1, 2, 3)
1 2 3

Adding optional arguments with default values to the functions we define turns out to be pretty easy:

向我们定义的函数添加带有默认值的可选参数非常简单:

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")
Hello, Colin
Hello, Kaggle
Hello, world

Functions Applied to Functions

Here's something that's powerful, though it can feel very abstract at first. You can supply functions as arguments to other functions. Some example may make this clearer:

函数应用于函数

这是一个很强大的东西,尽管一开始可能会感觉很抽象。 您可以提供函数作为其他函数的参数。 一些例子可能会让这一点更清楚:

def mult_by_five(x):
    return 5 * x

def 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
)
5
25

Functions that operate on other functions are called "higher-order functions." You probably won't write your own for a little while. But there are higher-order functions built into Python that you might find useful to call.

Here's an interesting example using the max function.

By default, max returns the largest of its arguments. But if we pass in a function using the optional key argument, it returns the argument x that maximizes key(x) (aka the 'argmax').

对其他函数进行操作的函数称为高阶函数。 您可能有一段时间不会自己编写。 但是 Python 中内置了一些高阶函数,您可能会发现调用这些函数很有用。

这是一个使用max函数的有趣示例。

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

def mod_5(x):
    """Return the remainder of x after dividing by 5"""
    return x % 5

print(
    'Which number is biggest?',
    max(100, 51, 14),
    'Which number is the biggest modulo 5?',
    max(100, 51, 14, key=mod_5),
    sep='\n',
)
Which number is biggest?
100
Which number is the biggest modulo 5?
14

Your Turn

Functions open up a whole new world in Python programming. Try using them yourself.

到你了

函数为 Python 编程开辟了一个全新的世界。 自己尝试使用它们

functions-and-getting-help【函数和获取帮助】

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top