在Python函数定义中并不允许在参数中用“/”和“”,但python3.8之后的文档中,函数参数中经常会出现斜杠“/”和星号“”,这两个符号单独出现时的意义如下。
斜杠:“/”用来指明位于“/”前面的函数参数必须使用位置参数而非关键字参数的形式,但对于其后面的参数不做限定。
help(divmod)
Help on built-in function divmod in module builtins:
divmod(x, y, /) # 斜杠前面只能是位置参数
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
input()中的提示性文字只能按位置传递,不能用关键字参数:
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
text = input('请输入你的姓名:') # 提示性文字是按位置传递进来的参数
# 先输出'请输入你的姓名:',不换行,等待用户输入后换行
print(text) # 当新的一行输出用户输入的字符串
# 提示性文字只能按位置传递,不能用关键字参数
text = input(prompt='请输入你的姓名:') # 触发异常
print(text) # TypeError: input() takes no keyword arguments
Traceback (most recent call last):
File “F:\weiyun\2020\19 测试文件\444.py”, line 3, in
text = input(prompt=’请输入你的姓名:’)
TypeError: input() takes no keyword arguments
# sum(iterable, /, start=0) # 斜杠前面是位置参数,不限制后面参数形式
# sum(iterable[, start]) # 3.7及以前版本
print(sum(range(101), start=5000)) # 10050
print(sum(range(101), 5000)) # 10050
print(sum([1, 2, 3, 4], 10)) # 20, 10参数start的值
# sum()函数最多只接受2个参数
print(sum([1, 2, 3, 4], 10, 20))
# TypeError: sum() takes at most 2 arguments (3 given)
星号:“”单独出现在参数中表示“”后面的参数必须为关键字参数的形式
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
print(sorted(['5', '2', '11', '6'], key=int)) # key必须用关键字参数
# ['2', '5', '6', '11']
print(sorted(['5', '2', '11', '6'], int)) # key不能用位置参数
# TypeError: sorted expected 1 argument, got 2
max(iterable, *[, key, default])
print(max(['5', '91', '111', '0006'], key=int)) # 111
print(max(['5', '91', '111', '0006'], key=len)) # 0006
print(max(['5', '91', '111', '0006'], len))
# 此时len被当成参与比较的对象,不是key值
# TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'list'