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
- default arguments
- keyword arguments
- positional arguments
- arbitrary positional arguments
- 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
#!/usr/bin/env python3
# coding: utf8
def func_args(arg1: int, arg2: str = None, arg3: float = 1.0, arg4: bool = True):
print("arg1 {}".format(arg1))
print("arg2 {}".format(arg2))
print("arg3 {}".format(arg3))
print("arg4 {}".format(arg4))
print("\n")
# 全部使用匿名参数 ✅
func_args(60, "LEDs", 0.2, False)
# 全部使用匿名参数 ✅
func_args(arg1=60, arg2="LEDs", arg3=0.2, arg4=False)
# 混合使用,前面匿名参数,后面具名参数 ✅
func_args(60, "LEDs", arg3=0.2, arg4=False)
# 混合使用,前面匿名参数,中间具名参数,后面匿名参数 ❌
# func_args(60, "LEDs", arg3=0.2, False)
# Positional argument cannot appear after keyword arguments Pylance ❌
"""
positional argument / keyword arguments
https://www.cnblogs.com/xgqfrms/p/17451650.html#5182186
https://docs.python.org/3/library/typing.html
"""
$ chmod +x ./function-pass-multi-args.py
$ ./function-pass-multi-args.py
(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://www.cnblogs.com/xgqfrms/p/17451650.html#5182186
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!
- function argument Python All Onefunction argument python all arguments function python check python method all one exceptions python all one python all one in python errors all one function compare typescript arguments function-like arguments included function python alias all one python files all one