Python function argument All In One

xgqfrms / 2023-06-02 / 原文

Python function argument All In One

Python 函数参数

https://docs.python.org/3/library/typing.html

https://docs.python.org/3/library/typing.html#typing.ParamSpec.args

function argument types

  1. default arguments
  2. keyword arguments
  3. positional arguments
  4. arbitrary positional arguments
  5. arbitrary keyword arguments

https://levelup.gitconnected.com/5-types-of-arguments-in-python-function-definition-e0e2a2cafd29

https://pynative.com/python-function-arguments/

强制位置参数

Python 3.8 新增了一个函数形参语法:

/, 用来指明前面的函数形参必须使用指定位置参数,不能使用关键字参数的形式;
*, 用来指明后面的函数形参必须使用指定关键字参数,不能使用位置参数的形式;

在以下的例子中,a 和 b 必须使用位置形参 ,c 或 d 可以是位置形参或关键字形参,而 e 和 f 必须使用关键字形参:

def f(a, b, /, c, d, *, e, f):
    print("位置参数", a, b)
    print("c 或 d 可以是位置形参或关键字形参", c, d)
    print("关键字参数", e, f)
    # print(a, b, c, d, e, f)

# 正确的使用方法 ✅
f(10, 20, 30, d=40, e=50, f=60)

# 错误的使用方法 ❌
# b 不能使用关键字形参
f(10, b=20, c=30, d=40, e=50, f=60)

# e 不能使用位置形参
f(10, 20, 30, 40, 50, f=60)

https://www.runoob.com/python3/python3-function.html

demos


$  chmod +x ./function-pass-multi-args.py
$ ./function-pass-multi-args.py
arg1 60
arg2 LEDs
arg3 0.2
arg4 False

arg1 60
arg2 LEDs
arg3 0.2
arg4 False

arg1 60
arg2 LEDs
arg3 0.2
arg4 False

image

#!/usr/bin/env python3
# coding: utf8

def f(a, b, /, c, d, *, e, f):
    print("位置参数", a, b)
    print("c 或 d 可以是位置形参或关键字形参", c, d)
    print("关键字参数", e, f)
    # print(a, b, c, d, e, f)

# 正确的使用方法 ✅
f(10, 20, 30, d=40, e=50, f=60)

# 错误的使用方法 ❌
# b 不能使用关键字形参
f(10, b=20, c=30, d=40, e=50, f=60)

# e 不能使用位置形参
f(10, 20, 30, 40, 50, f=60)

$ pyhthon3 ./function-mix-args.py
# OR
$ py3 ./function-mix-args.py
位置参数 10 20
c 或 d 可以是位置形参或关键字形参 30 40
关键字参数 50 60
Traceback (most recent call last):
  File "/Users/xgqfrms-mm/Documents/github/Raspberry-Pi/Pi-4B/ws2812b-led-strip/./function-mix-args.py", line 15, in <module>
    f(10, b=20, c=30, d=40, e=50, f=60)
TypeError: f() got some positional-only arguments passed as keyword arguments: 'b'

image

refs



©xgqfrms 2012-2021

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!