18. Python-位置参数

16 阅读1分钟

解压可迭代对象中的位置参数

  • *args:args ,以列表返
list1 = [1, 2, 3, 4, 5]
head, *tail= list1
print("head", head) # head 1
print("tail", tail) # tail [2, 3, 4, 5]
  • 如果你想丢弃一些元素,可以使用 *_
list1 = [1, 2, 3, 4, 5]
head, *_, tail = list1
print("head", head) # head 1
print("tail", tail) # tail 5

函数形参中的位置参数

  • 位置限定参数 /,该参数之前只能通过位置传递,不能通过关键字
def greet(name, /, age):
    print(f"Hello, {name}! You are {age} years old")

greet("Alice", 30) #√
greet("Alice", age=30) #√
greet(name="Alice", age=30) 
  • 关键字限定参数 *,该参数之后只能通过关键字传递,不能通过位置传递
def greet(name, *, age):
    print(f"Hello, {name}! You are {age} years old")

greet("Alice", 30) 
greet("Alice", age=30) #√    
greet(name="Alice", age=30) #√
  • 可变位置参数 *args,以元组返
def add(*args):
    total = 0
    for i in args:
        total += i
    return total

total = add(1, 2, 3, 4, 5)
print("total",total) # total 15
  • 可变关键字参数 **kwargs,以字典返
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key} : {value}")

print_info(name="Alice", age=30, city="Beijing")
# name : Alice
# age : 30
# city : Beijing