<
>

Python入门之Python函数

2020-06-28 14:44:40 来源:易采站长站 作者:易采站长站整理

依据默认参数必须在位置参数之后的原则
,那么
/
*
之间的位置或关键字参数在
函数定义时
只能通过
kwarg=value
的形式定义,否则会报错,不过
调用时
位置参数和关键字参数的传入方式都可以。但
*
之后的仅关键字参数不受影响,可以不设置默认值,但是调用必须用关键字参数的形式调用。Python 3.8 中测试如下:

# 错误定义:仅位置参数有默认值,/ 和 * 的位置或关键字参数需用 kwarg=value 定义
# SyntaxError: non-default argument follows default argument
def my_fun(name, age=12, /, nation, *, city):
print(f'我的名字是:{name},今年{age}岁,来自{nation},现居{city}')

# 正确定义一:关键字参数不设置默认值
def my_fun(name, age=12, /, nation='中国', *, city):
print(f'我的名字是:{name},今年{age}岁,来自{nation},现居{city}')

# 正确定义二:关键字参数设置默认值
def my_fun(name, age=12, /, nation='中国', *, city='武汉'):
print(f'我的名字是:{name},今年{age}岁,来自{nation},现居{city}')

# 错误调用一:仅位置参数不能通过关键字参数形式传入
my_fun('Jock', age=25) # TypeError: my_fun() got some positional-only arguments passed as keyword arguments: 'age'
# 正确调用一
my_fun('Jock', 25) # Correct

# 正确调用二
my_fun('Jock', 25, '中国') # Correct

# 正确调用三
my_fun('Jock', 25, nation='中国') # Correct

# 错误调用二:仅关键字参数不能通过位置参数的形式传入
my_fun('Jock', 25, '中国', '武汉') # TypeError: my_fun() takes from 1 to 3 positional arguments but 4 were given

# 正确调用四
my_fun('Jock', 25, nation='中国', city='桂林') # Correct

了解了这些,以后我们再也不用担心不会正确的定义函数,也不用担心看不懂函数中的

/
*
,可以轻松的调用函数。比如 Python 中的
list
对象的
index
方法,我们可以使用
help(list.index)
查看它的用法如下:

>>> help(list.index)
Help on method_descriptor:

index(self, value, start=0, stop=2147483647, /)
Return first index of value.

Raises ValueError if the value is not present.

我们可以看到 index 函数有 4 个参数, self, value, start, stop, 其中 start 和 stop 有默认值,里面还有一个

暂时禁止评论

微信扫一扫

易采站长站微信账号