功能

引言

代码中的某些任务可能会多次执行。比方说你不仅要向世界而且要向很多人说“你好”。你就得写下

print('Hello, {name}!')

太多次了。如果我们能写的话它会短得多

greet('{name}')

它会直接打印出来 Hello, {{name}}! 。好的,不是那么短……但是假设您想要找到某些函数的根。涉及的代码要多得多,如果能有一个漂亮的快捷方式来执行所有这些代码,而不需要反复编写代码,那就太好了,不是吗?这是符合 DRY 原则!作为一个很好的副作用,如果您发现错误或想要使用一些更复杂的例程,您只需在代码的一个位置而不是所有位置更改例程。

但是,即使您确实只在程序中使用了一次代码片段,给它起一个简短的名称并将实现隐藏在其他地方可能会更具声明性。这也可以帮助您 divide and conquer 更大的问题!

好的是您已经知道了一个函数: print() 好了!您是这样使用它的:

print('Hello, World!')

让我们仔细看看组成函数的各个部分。

函数的组件

名字

大多数函数都有名称 1. 的名称 print() 是--永远也猜不到-- 打印 。打印该函数而不调用它会显示它是一个内置函数:

>>> print(print)
<built-in function print>

还有更多 Built-in Functions 举个例子,在他们当中, float()

位置论元

float() 是一个函数,用于将表示数字的数字或字符串转换为浮点数。其接口定义为

float(x)

哪里 x 是它的论据。更准确地说,它是它的 位置论元 。通过调用 float() 并将整数作为参数传递,结果是相应的浮点数:

>>> float(1)
1.0
>>> float(-2)
-2.0

还可以将表示数字的字符串传递给 float()

>>> float('1')
1.0
>>> float('-2')
-2.0
>>> float('1.500')
1.5
>>> float('1e-2')
0.01
>>> float('+1E6')
1000000.0

对于INTEGER也存在类似的函数。它是一种功能 int()

关键字参数

int() 是一个函数,用于将表示数字的数字或字符串转换为整数。其接口定义为

int(x, base=10)

哪里 x 是它的 位置论元base 是它的 关键字参数 。虽然位置参数必须传递给函数,但关键字参数是可选的,并提供默认值。的默认值 base10

将浮点数传递给 int() 小数点后的所有内容都将被删除:

>>> int(1.0)
1
>>> int(-2.0)
-2
>>> int(1.3)
1
>>> int(1.8)
1
>>> int(-1.3)
-1
>>> int(-1.8)
-1

将字符串传递给 int() 这个 base 关键字参数用于指示应如何根据给定的基数解释数字。

>>> int('1')
1
>>> int('-2')
-2
>>> int('101010')
101010
>>> int('101010', base=2)
42

您不必写出关键字参数,它们的解释顺序与它们在界面中的顺序相同:

>>> int('101010', 2)
42

但您不能将表示浮点数的字符串转换为整数,如下所示:

>>> int('1.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.0'

要做到这一点,你必须用链条 int()float()

>>> int(float('1.0'))
1

定义函数

函数的定义方式是以 def 关键字。随后,您需要在括号中提供函数的名称及其参数。然后,您可以像使用已经使用的函数一样使用它。

>>> def greet(name):
...     print('Hello', name)
...
>>> greet('World')
Hello World
>>> greet('you')
Hello you
>>> def add_reciprocal(a, b):
...     return 1/a + 1/b
>>> add_reciprocal(4, 8)
0.375

要提供关键字参数,您可以通过为参数赋值来使其具有默认值:

>>> def name_and_favorite_food(name, favorite_food='pizza'):
...     return name + "'s favorite food is " + favorite_food + '.'
...
>>> name_and_favorite_food('Dominik')
"Dominik's favorite food is pizza."
>>> name_and_favorite_food('Stefan', 'kimchi')
"Stefan's favorite food is kimchi."

如果在交互式Python解释器中执行它们,则函数返回的值会自动显示(如果您没有将其赋给变量)。重要的是要知道 return 关键字用于使外部作用域(即函数外部)可以访问该值。请参见下面的示例,其中我们首先没有RETURN语句:

>>> def is_positive_without_return(x):
...     if x >= 0:
...         print(True)
...     else:
...         print(False)
...
>>> is_positive_without_return(1)
True
>>> is_positive_without_return(-1)
False
>>> a = is_positive_without_return(1)
True
>>> print(a)
None

如您所见,变量 a 一点价值都没有。如果你想要的话 a 要接收函数的结果,您必须返回它,而不是打印它:

>>> def is_positive_without_return(x):
...     if x >= 0:
...         return True
...     else:
...         return False
...
>>> is_positive_without_return(1)
True
>>> is_positive_without_return(-1)
False
>>> a = is_positive_without_return(1)
>>> print(a)
True

函数作为函数参数

您可以将几乎任何内容传递给函数-甚至函数本身!如果要对数学函数进行数据拟合或求根,这尤其有用。

def format_heading(text):
    return '\n' + text + '\n' + '='*len(text) + '\n'

def prettify(sections, header_formatter):
    # Assume that `sections` is a list of dictionaries with the keys
    # ``heading`` for the heading text and ``content`` for the content
    # of the section.
    # Assume that the `header_formatter` is a function that takes a string
    # as argument and formats it in a way that is befitting for a heading.
    text = ''
    for section in sections:
        heading = section['heading']
        content = section['content']
        text += format_heading(heading) + content + '\n'
    # Before returning it we make shure that all surrounding whitespace is
    # gone.
    return text.strip()

secs = [
    {
        'heading': 'Introduction',
        'content': 'In this section we introduce some smart method to teach Python.'
    },
    {
        'heading': 'Results',
        'content': 'More than 42 % of participants in this study learned Python.'
    }
]

pretty_text = prettify(secs, header_formatter=format_heading)
print(pretty_text)

所以你可以看到这个论点 header_formatter 只是把它当作一个函数来对待。如果运行此脚本,则输出将为:

Introduction
============
In this section we introduce some smart method to teach Python.

Results
=======
More than 42 % of participants in this study learned Python.

摘要

  • 通过简化重复任务或为复杂的编程逻辑命名,函数可以使您的工作变得更轻松。

  • 函数可以有两种不同类型的参数, 位置论元 必须提供给函数的 关键字参数 它们提供默认值。

  • 函数是使用 def 关键字。

  • 函数可以通过使用 return 关键字。

练习

脚注

1

Lambdas 是规则的例外,因为它们定义匿名函数。