Python学习(六)---函数

来源:互联网 发布:零售大数据分析 编辑:程序博客网 时间:2024/05/15 05:55

函数调用
要调用一个函数,需要知道函数的名称和参数
函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”:

>>> a = abs # 变量a指向abs函数>>> a(-1) # 所以也可以通过a调用abs函数1

函数定义
在Python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回。
例如:

def my_abs(x):    if x >= 0:        return x    else:        return -xdef nop():  #空函数    pass

参数检查,调用函数时,如果参数个数不对,Python解释器会自动检查出来,并抛出TypeError:

>>> my_abs(1, 2)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: my_abs() takes 1 positional argument but 2 were given

但是如果参数类型不对,Python解释器就无法帮我们检查。

>>> my_abs('A')Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 2, in my_absTypeError: unorderable types: str() >= int()>>> abs('A')Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: bad operand type for abs(): 'str'

isinstance()参数类型检查:

def my_abs(x):    if not isinstance(x, (int, float)):        raise TypeError('bad operand type')    if x >= 0:        return x    else:        return -x

返回多个值

import mathdef move(x, y, step, angle=0):    nx = x + step * math.cos(angle)    ny = y - step * math.sin(angle)    return nx, ny >>> x, y = move(100, 100, 60, math.pi / 6)

但其实这只是一种假象,Python函数返回的仍然是单一值,实际上返回的是一个tuple。

可变参数
在Python函数中,还可以定义可变参数。顾名思义,可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个

利用list或tuple实现可变参数

def calc(numbers):    sum = 0    for n in numbers:        sum = sum + n * n    return sum>>> calc([1, 2, 3]) #先组装一个list14

但是调用的时候,需要先组装出一个list或tuple。

下面看看真正的可变参数如何实现:

def calc(*numbers):    sum = 0    for n in numbers:        sum = sum + n * n    return sum>>> calc(1, 2)5>>> calc()0>>> nums = [1, 2, 3]>>> calc(*nums) #Python允许你在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进去14

关键字参数

0 0
原创粉丝点击