Python函数参数全攻略

 更新时间:2025年11月29日 10:01:57   作者:布玛&  
文章介绍了Python函数参数的六种类型:普通参数、可变位置参数、可变关键字参数、混合使用所有参数类型、参数解包以及参数顺序规则,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧

1.普通参数 (没有星号)

2.可变位置参数 (*args)

使用单个星号 *,将多个位置参数打包成元组

def func(*nums):
    print(f"nums: {nums}, type: {type(nums)}")
func(1, 2, 3)          # nums: (1, 2, 3), type: <class 'tuple'>
func('a', 'b')         # nums: ('a', 'b'), type: <class 'tuple'>
func()                 # nums: (), type: <class 'tuple'>
python
def calculate_sum(*numbers):
    return sum(numbers)
print(calculate_sum(1, 2, 3))        # 6
print(calculate_sum(10, 20, 30, 40)) # 100

**3.可变关键字参数 (kwargs)

使用两个星号 **,将多个关键字参数打包成字典

def func(**nums):
    print(f"nums: {nums}, type: {type(nums)}")
func(a=1, b=2, c=3)    # nums: {'a': 1, 'b': 2, 'c': 3}, type: <class 'dict'>
func(name="Alice")     # nums: {'name': 'Alice'}, type: <class 'dict'>
func()                 # nums: {}, type: <class 'dict'>
def create_user(**user_info):
    user = {
        'name': 'Unknown',
        'age': 0,
        'email': ''
    }
    user.update(user_info)  # 用传入的参数更新默认值
    return user
user1 = create_user(name="Alice", age=25)
user2 = create_user(name="Bob", email="bob@example.com")

4.混合使用所有参数类型

def complex_func(required, *args, **kwargs):
    print(f"必需参数: {required}")
    print(f"可变位置参数: {args}")
    print(f"可变关键字参数: {kwargs}")
complex_func("hello", 1, 2, 3, name="Alice", age=25)
# 输出:
# 必需参数: hello
# 可变位置参数: (1, 2, 3)
# 可变关键字参数: {'name': 'Alice', 'age': 25}

5.参数解包

def func(a, b, c):
    print(f"a={a}, b={b}, c={c}")
# 参数解包
numbers = [1, 2, 3]
func(*numbers)  # 相当于 func(1, 2, 3)
params = {'a': 10, 'b': 20, 'c': 30}
func(**params)  # 相当于 func(a=10, b=20, c=30)
def student_info(name, age, *scores, **additional_info):
    print(f"学生: {name}, 年龄: {age}")
    print(f"成绩: {scores}")
    print(f"附加信息: {additional_info}")
# 使用示例
student_info("张三", 20, 85, 90, 78, city="北京", hobby="篮球")
# 输出:
# 学生: 张三, 年龄: 20
# 成绩: (85, 90, 78)
# 附加信息: {'city': '北京', 'hobby': '篮球'}

6.参数顺序规则:

在函数定义中,参数必须按以下顺序排列:
普通参数
*args 参数
**kwargs 参数

# 这是错误的!
# def wrong_order(**kwargs, *args, a, b):
#     pass

到此这篇关于Python函数参数全攻略的文章就介绍到这了,更多相关Python函数参数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论