Python精选

Python函数那点事

2019-02-27  本文已影响0人  淡定_蜗牛

在同一程序中需要多次重复使用相同的代码。功能帮助我们这样做。我们在函数中重复编写我们必须要做的事情,然后在需要的地方调用它。我们已经看到了像len(),divmod()这样的函数 。

定义函数

我们使用def关键字来定义一个函数。一般语法就像

def functionname(params):
    statement1
    statement2

让我们编写一个函数,它将两个整数作为输入,然后返回总和。

>>> def sum(a, b):
...     return a + b

在带有return关键字的第二行中,我们将a + b的值发送回 调用者。你必须这样称呼它

>>> res = sum(234234, 34453546464)
>>> res
34453780698L

还记得我们在上一章写的回文程序。让我们编写一个函数来检查给定的字符串是否是回文,然后返回 True或False。

#!/usr/bin/env python3
def palindrome(s):
    return s == s[::-1]
if __name__ == '__main__':
    s = input("Enter a string: ")
    if palindrome(s):
        print("Yay a palindrome")
    else:
        print("Oh no, not a palindrome")

现在运行代码:)

本地和全局变量

为了理解局部和全局变量,我们将通过两个例子。

#!/usr/bin/env python3
def change(b):
    a = 90
    print(a)
a = 9
print("Before the function call ", a)
print("inside change function", end=' ')
change(a)
print("After the function call ", a)

输出

$ ./local.py
Before the function call  9
inside change function 90
After the function call  9

首先,我们正在分配9到一个,然后调用函数的变化,那里面我们分配90到一个和打印一个。函数调用后,我们再次打印的值一个。当我们在函数内写一个= 90时,它实际上创建了一个名为a的新变量,它只在函数内部可用,并在函数完成后被销毁。因此,尽管变量a的名称相同,但它们在函数的内外都不同。

#!/usr/bin/env python3
def change(b):
    global a
    a = 90
    print(a)
a = 9
print("Before the function call ", a)
print("inside change function", end=' ')
change(a)
print("After the function call ", a)

这里通过使用全局关键字,我们告诉a是全局定义的,所以当我们在函数内部改变一个值时,它实际上也在改变函数的外部。

输出

$ ./local.py
Before the function call  9
inside change function 90
After the function call  90

默认参数值

在函数中,变量可能具有默认参数值,这意味着如果我们不为该特定变量赋予任何值,则它将自动分配。

>>> def test(a , b=-99):
...     if a > b:
...         return True
...     else:
...         return False

在上面的例子中,我们在函数参数列表中写了b = -99。这意味着如果没有值b给出的则b的值是-99。这是默认参数的一个非常简单的示例。您可以通过测试代码

>>> test(12, 23)
False
>>> test(12)
True

重要
重要

请记住,如果您之前已经有一个带有默认值的参数,则不能使用默认参数。像f(a,b = 90,c)一样是非法的,因为b具有默认值,但在此之后c没有任何默认值。

还要记住,默认值只计算一次,所以如果你有像列表这样的可变对象,它会有所不同。请参阅下一个示例

>>> def f(a, data=[]):
...     data.append(a)
...     return data
...
>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]

为了避免这种情况,您可以编写更多惯用的Python,如下所示

>>> def f(a, data=None):
...     if data is None:
...         data = []
...     data.append(a)
...     return data
...
>>> print(f(1))
[1]
>>> print(f(2))
[2]

关键字参数

>>> def func(a, b=5, c=10):
...     print('a is', a, 'and b is', b, 'and c is', c)
...
>>> func(12, 24)
a is 12 and b is 24 and c is 10
>>> func(12, c = 24)
a is 12 and b is 5 and c is 24
>>> func(b=12, c = 24, a = -1)
a is -1 and b is 12 and c is 24

在上面的例子中,您可以看到我们正在调用具有变量名称的函数,例如func(12,c = 24),我们将24分配给c并且b正在获取其默认值。还要记住,在基于关键字的参数之后,您不能没有基于关键字的参数。喜欢

>>> def func(a, b=13, v):
...     print(a, b, v)
...
File "<stdin>", line 1
SyntaxError: non-default argument follows default argument

仅关键字参数
我们还可以将函数的参数标记为仅关键字。这样,在调用该函数时,将强制用户为每个参数使用正确的关键字。

>>> def hello(*, name='User'):
...     print("Hello %s" % name)
...
>>> hello('Kushal')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: hello() takes 0 positional arguments but 1 was given
>>> hello(name='Kushal')
Hello Kushal

文档字符串

在Python中,我们使用docstrings来解释如何使用代码,它将在交互模式中有用并创建自动文档。下面我们看一个名为longest_side的函数的docstring示例。

#!/usr/bin/env python3
import math

def longest_side(a, b):
    """
    Function to find the length of the longest side of a right triangle.

    :arg a: Side a of the triangle
    :arg b: Side b of the triangle

    :return: Length of the longest side c as float
    """
    return math.sqrt(a*a + b*b)

if __name__ == '__main__':
    print(longest_side(4, 5))

我们将在reStructuredText章节中详细了解docstrings。

高阶函数

高阶函数或仿函数是至少执行以下步骤之一的函数:

将一个或多个函数作为参数。
返回另一个函数作为输出。
在Python中,任何函数都可以充当高阶函数。

>>> def high(func, value):
...     return func(value)
...
>>> lst = high(dir, int)
>>> print(lst[-3:])
['imag', 'numerator', 'real']
>>> print(lst)

Map功能

map是Python中一个非常有用的高阶函数。它需要一个函数和一个迭代器作为输入,然后在迭代器的每个值上应用函数并返回结果列表。

例:

>>> lst = [1, 2, 3, 4, 5]
>>> def square(num):
...     "Returns the square of a given number."
...     return num * num
...
>>> print(list(map(square, lst)))
[1, 4, 9, 16, 25]
image

欢迎大家关注公众号:「Python精选」,关注公众号,回复「1024」你懂得,免费领取 6 本经典Python编程书籍。关注我,与 10 万程序员一起进步。每天更新Python干货哦,期待你的到来!

上一篇 下一篇

猜你喜欢

热点阅读