马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册
×
Python 3.12.1 (tags/v3.12.1:2305ca5, Dec 7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
一、位置参数(join是指定分隔符拼接的函数,join适用于把这些字符串连接起来,join函数需要接可迭代对象作为参数,所以内层小括号实际上是元组。””相当于分隔符。
def myfunc(s,vt,o):
return "".join((o,vt,s))
myfunc("我","打了","小姐姐")
'小姐姐打了我'
myfunc("小姐姐","打了","我")
'我打了小姐姐'
二、关键字参数
myfunc(o="我",vt="打了",s="小姐姐")
'我打了小姐姐'
myfunc(o="我","打了","小姐姐")
SyntaxError: positional argument follows keyword argument (报错原因:位置参数必须在关键字参数之前,和format一样)
三、默认参数
def myfunc(s,vt,o="小姐姐"):
ruturn "".join((o,vt,s))
SyntaxError: invalid syntax
def myfunc(s,vt,o="小姐姐"):
return "".join((o,vt,s))
myfunc("香蕉","吃")
'小姐姐吃香蕉'
myfunc("香蕉","吃","小帅哥") (给定第三个参数,第三个参数就会覆盖默认值)
'小帅哥吃香蕉'
def myfunc(s="苹果",vt,o="小姐姐"):
return "".join((o,vt,s))
SyntaxError: parameter without a default follows parameter with a default (报错原因:位置参数必须在关键字参数之前)
def myfunc(vt,s="苹果",o="小姐姐"):
return "".join((o,vt,s))
myfunc("吃了")
'小姐姐吃了苹果'
四、help()参数查看函数文档
help(abs)
Help on built-in function abs in module builtins:
abs(x, /) (abs指定返回数值的绝对值)
Return the absolute value of the argument.
help(sum)
Help on built-in function sum in module builtins:
sum(iterable, /, start=0)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
这里abs()和sun()的函数文档中都出现了斜杠”/”,这个“/”斜杠代表什么意思呢?斜杠左侧的参数它必须传递位置参数,不能是关键字参数。
abs(-1.5)
1.5
abs(x=-1.5)
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
abs(x=-1.5)
TypeError: abs() takes no keyword arguments (报错原因:从参数原型abs(x,/)中知道,这个参数的形参的名字叫x,如果存入abs(x=-1.5),那它是会报错的,因为参数原型abs(x,/)中多了一个“/”,斜杠“/”左侧是不能使用关键字参数,只能使用位置参数去传递的)
sum([1,2,3],4)
10
sum([1,2,3],start=4)
10
def abc(a,/,b,c): (abc就是随便自定义的函数)
print(a,b,c)
abc(1,2,3) (都是位置参数,没问题)
1 2 3
abc(a=1,2,3)
SyntaxError: positional argument follows keyword argument (报错原因:斜杠左边不能支持关键字参数的)
abc(3,b=2,c=1) (斜杠右侧随意,可是位置参数,也可是关键字参数)
3 2 1
既然有限制只能使用位置参数的,那有没有那种限制只能使用关键字参数的语法呢?还真有。用“*”星号,“*”星号左边既可以是位置参数,也可以是关键字参数,但右侧的参数如下面的b和c就只能是关键字参数,才不会报错。
def abc(a,*,b,c):
print(a,b,c)
abc(1,2,3)
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
abc(1,2,3)
TypeError: abc() takes 1 positional argument but 3 were given (报错原因:“*”左边既可以是位置参数,也可以是关键字参数,但右侧的参数就只能是关键字参数)
abc(a=1,b=2,c=3)
1 2 3
abc(1,b=2,c=3)
1 2 3
|