Python 函数详解

在 Python 中,函数是一种重要的程序结构,用于组织和封装可重复使用的代码块。函数允许开发者将一段特定的逻辑或功能封装成一个独立的单元,并通过函数名和参数列表进行调用。

Python 作为一种语法灵活的编程语言,其函数也有自己的一些特点,本篇教程将会从以下几方面来掌握 Python 函数的相关内容:

  1. 函数定义和调用
  2. 函数参数类型声明
  3. 函数不定长参数
  4. 函数返回值
  5. 匿名函数

1. 函数定义和调用

# 1. 函数定义语法
def demo1(a, b, c):
    result = a + b + c
    return result

def demo2(a, b=20, c=30):
    result = a + b + c
    return result


# 2.函数调用语法
# 2.1 位置参数
result1 = demo1(10, 20, 30)
result2 = demo2(10, 20, 30)
print(result1, result2)

# 2.2 关键字参数
result1 = demo1(a=10, b=20, c=30)
result2 = demo2(b=20, c=30, a=10)
print(result1, result2)

# 2.3 混合方式
# 位置参数在前,关键字参数在后
result3 = demo1(10, c=30, b=20)
print(result3)
result3 = demo2(10, c=30)
print(result3)

程序执行结果:

60 60
60 60
60
60

2. 函数参数类型声明

def demo3(a : int, b : float, c : str) -> str:
    print("a:", a, type(a))
    print("b:", b, type(b))
    print("c:", c, type(c))

demo3(10, 3.14, "abc");
# 注意: 参数的类型声明并不能强制限制参数的类型

# 如果要限定参数的类型,需要额外的判断
demo3(3.14, "abc", 18);
# 如下方式严格限时参数类型
def demo4(a : int, b : float, c : str) -> str:

    assert isinstance(a, int)
    assert isinstance(b, float)
    assert isinstance(c, str)

    print("a:", a, type(a))
    print("b:", b, type(b))
    print("c:", c, type(c))

demo3(10, 3.14, "abc");
demo4(3.14, "abc", 18);

程序执行结果:

a: 10 <class 'int'>
b: 3.14 <class 'float'>
c: abc <class 'str'>
a: 3.14 <class 'float'>
b: abc <class 'str'>
c: 18 <class 'int'>
a: 10 <class 'int'>
b: 3.14 <class 'float'>
c: abc <class 'str'>
Traceback (most recent call last):
  File "/Users/meng/NLP项目/BLOG内容/Python飞机大战/01-变量语法.py", line 23, in <module>
    demo4(3.14, "abc", 18);
  File "/Users/meng/NLP项目/BLOG内容/Python飞机大战/01-变量语法.py", line 14, in demo4
    assert isinstance(a, int)
AssertionError

3. 函数不定长参数

# 1. 不定长位置参数
print('-------位置不定长参数--------');
def demo1(*args):
    print("参数数量:", len(args))
    print("参数数据:", args)

    # 通过下标访问参数
    print(args[0], args[1], args[2], args[3])
    # 通过循环遍历参数
    for param in args:
        print(param)

demo1(10, 20, 30, 40)


# 2. 不定长关键字参数
print('-------关键字不定长参数--------');
def demo2(**kwargs):
    print("参数数量:", len(kwargs))
    print("参数数据:", kwargs)

    # 通过下标访问参数
    print(kwargs['a'], kwargs['b'], kwargs['c'], kwargs['d'])
    # 通过循环遍历参数
    for key, value in kwargs.items():
        print(key, value)

demo2(a=10, c=20, b=30, d=40)


# 3. 混合不定长参数
print('-------混合不定长参数--------');
# 注意: 位置参数在前,关键字参数在后
def demo3(a, b, *args, **kwargs):
    print(a)
    print(b)
    print(args)
    print(kwargs)

demo3(10, 20, 30, 40, 50, c=100, d=200)
print('--------------------')
demo3(10, 20, c=100, d=200)
print('--------------------')
demo3(10, 20, 30, 40, 50)

程序运行结果:

-------位置不定长参数--------
参数数量: 4
参数数据: (10, 20, 30, 40)
10 20 30 40
10
20
30
40
-------关键字不定长参数--------
参数数量: 4
参数数据: {'a': 10, 'c': 20, 'b': 30, 'd': 40}
10 30 20 40
a 10
c 20
b 30
d 40
-------混合不定长参数--------
10
20
(30, 40, 50)
{'c': 100, 'd': 200}
--------------------
10
20
()
{'c': 100, 'd': 200}
--------------------
10
20
(30, 40, 50)
{}

4. 函数返回值

# 1. 返回单个值
def demo1():
    return 100


# 2. 返回多个值
def demo2():
    return 10, 3.14, "abc"


# 单个变量保存返回结果
result = demo2()
print(result)
# 多个变量保存返回结果
result1, result2, result3 = demo2()
print(result1, result2, result3)

5. 匿名函数

from typing import Callable, get_origin, get_args


# 1. 函数作为函数参数
def do_logic(a : int, b : int, func : Callable[[int, int], int]) -> int:
    assert isinstance(a, int)
    assert isinstance(b, int)
    assert callable(func)

    result = func(a, b)
    return result

def my_logic1(a, b):
    return a - b

def my_logic2(a, b):
    return a + b

result = do_logic(10, 20, my_logic1)
print(result)
result = do_logic(10, 20, my_logic2)
print(result)


# 2. 匿名函数作为参数
# 如果函数复杂,并不是简单单行函数,则不可以使用匿名函数
result = do_logic(10, 20, lambda a, b: a - b)
print(result)
result = do_logic(10, 20, lambda a, b: a + b)
print(result)

未经允许不得转载:一亩三分地 » Python 函数详解
评论 (0)

2 + 7 =