zoukankan      html  css  js  c++  java
  • Python

    前置知识

    Python 函数:https://www.cnblogs.com/poloyy/p/15092393.html

    什么是仅限位置形参

    • 仅限位置形参是 Python 3.8 才有的新特性
    • 新增了一个函数形参语法 /
    • 添加了它,表示函数形参只能通过位置参数传递,而不能通过关键字参数形式传递

    仅限位置形参栗子

    def test1(a, b, c):
        print(a, b, c)
    
    
    test1(a=1, b=2, c=3)
    
    
    def test(a, /, b, c):
        print(a, b, c)
    
    
    # 正确
    test(1, b=2, c=3)
    test(*(1,), b=2, c=3)
    
    # 错误
    test(a=1, b=2, c=3)
    
    
    1 2 3
    1 2 3
    1 2 3
    
        test(a=1, b=2, c=3)
    TypeError: test() got some positional-only arguments passed as keyword arguments: 'a'
    • 报错信息:test() 得到一些作为关键字参数传递的仅位置参数 ‘a'
    • 在 / 形参的参数只能通过位置参数传递

    什么是仅限关键字参数

    • 和仅位置参数一样,也是 Python 3.8 的新特性
    • 参数只传 * 代表仅关键字参数
    • 添加了它,表示函数形参只能通过关键字参数传递,而不能通过位置参数传递

     仅限关键字参数栗子

    def f1(a, *, b, c):
        return a + b + c
    
    
    # 正确
    f1(1, b=2, c=3)
    f1(1, **{"b": 2, "c": 3})
    
    # 错误
    f1(1, 2, c=3)
    
    
    # 输出结果
    6
    6
    
        f1(1, 2, c=3)
    TypeError: f1() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given 
    • 报错信息:接受1个位置参数,但提供了2个位置参数(和1个仅限关键字的参数)
    • 在 * 形参的参数只能通过关键字参数传递

    / 和 * 混合栗子

    def f(a, /, b, *, c):
        print(a, b, c)
    
    
    # 正确
    f(1, 2, c=3)
    f(1, b=2, c=3)
    
    # 错误
    f(a=1, b=2, c=3)
    f(1, 2, 3)
    
    
    # 输出结果
    1 2 3
    1 2 3

    栗子二

    def f(a, b, /, c, *, d, e):
        print(a, b, c, d, e)
    
    
    # 正确
    f(1, 2, c=3, d=4, e=5)
    
    # 错误
    f(1, 2, 3, 4, 5)
    
    # 输出结果
    1 2 3 4 5 
  • 相关阅读:
    leetcode 21 Merge Two Sorted Lists
    leetcode 20 Valid Parentheses
    leetcode 19 Remove Nth Node From End of List
    [学习笔记]守护进程深入理解
    [学习笔记]父进程wait和waitpid
    [学习笔记]进程终止的5种方式
    [学习笔记]父子进程共享文件描述符理解
    [学习笔记]Vfork深入理解
    [学习笔记]_exit和exit深入理解
    [学习笔记]孤儿进程僵死进程
  • 原文地址:https://www.cnblogs.com/poloyy/p/15106522.html
Copyright © 2011-2022 走看看