定义函数

Python 最大的特色之一就是用缩进来表示层级关系,所以与 C/C++ 不同,它没有大括号,标准的定义格式如下:

1
2
3
def 函数名(参数列表):
函数体
return 返回值

有几点说明:

  • 不要忘记冒号

  • 与 C/C++ 相同,可以没有返回值,甚至可以没有 return 语句,在末尾自动返回

  • 如果传入的是可变数据(列表、字典和集合),那么对它们的修改是永久的,你可以使用切片([:])或深拷贝来规避这一特性

  • 不要混用 Tab 和空格,虽然有时它们看起来是一样的,这会让程序无法运行

简单的例子:

1
2
3
def area(width, height):
return width * height
print(area(3,4)) # 12

传递参数

因为 Python 中没有指针这种概念,所以没有地址传递这一说,如果是不可变类型就是值传递,可变类型就是引用传递

但是传参的写法对比 C/C++ 有了一些创新

位置实参

这就是类 C/C++ 的写法了,最普通常见的写法

1
2
3
4
def makeFullName(firstName, lastName):
return firstName + " " + lastName

print(makeFullName("John", "Smith")) # John Smith

关键字实参

在调用时手动指定形参的名称

1
2
3
4
5
def makeFullName(firstName, lastName):
return firstName + " " + lastName

print(makeFullName(firstName="John", lastName="Smith")) # John Smith
print(makeFullName(lastName="Smith", firstName="John")) # John Smith

设置默认值

这点与 C++ 中的相同

1
2
3
4
5
6
7
8
def makeFullName(firstName, lastName, middleName = ''):
if middleName:
return firstName + ' ' + middleName + ' ' + lastName
else:
return firstName + ' ' + lastName

print(makeFullName('John', 'Smith')) # John Smith
print(makeFullName('John', 'Smith', 'Paul')) # John Paul Smith

任意数量的实参

在 C/C++ 中,这个功能需要额外的库,但是 Python 是自带的

元组型

在参数列表使用 *元组名 来接收任意个参数,所有收到的参数都会保存在此元组中

1
2
3
def functionname([formal_args,] *var_args_tuple ):
function_suite
return [expression]

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)


make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

# Making a 16-inch pizza with the following toppings:
# - pepperoni

# Making a 12-inch pizza with the following toppings:
# - mushrooms
# - green peppers
# - extra cheese

字典型

在参数列表使用 **字典名 来接收任意个键值对,所有收到的键值对都会保存在此字典中

1
2
3
def functionname([formal_args,] **var_args_dict ):
function_suite
return [expression]

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile


user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)

# {'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

匿名函数

见此篇:python基础之匿名函数详解