功能

介绍

代码中的某些任务可能会执行很多次。说你不仅想对世界说“你好”,而且想对很多人说“你好”。你得写

print('Hello, {name}!')

很多次。如果我们能写的话会短很多

greet('{name}')

它就会打印出来 Hello, {{name}}! .好吧,没那么短…但是假设您想要找到一些函数的根。有更多的代码参与进来,并且有一个很好的快捷方式来执行所有的代码,而不需要反复地写它,是不是很好?这是在精神上的 DRY 原则!作为一个好的副作用,如果你发现了一个bug或者想使用一些更复杂的程序,你只需要在代码的一个地方而不是所有的地方改变程序。

但是,即使在程序中只使用一次代码片段,给它一个简短的名称并将实现隐藏在其他地方可能更具声明性。这也有助于你 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

整数也有类似的函数。它是功能 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 关键字。随后,在paranthesis中提供函数名及其参数。然后您可以像使用已经使用的函数那样使用它。

>>> 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 关键字用于使值可访问外部作用域,即函数外部。请参阅以下示例,其中我们首先没有返回语句:

>>> 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 是规则的例外,因为它们定义匿名函数。