|
发表于 2022-4-8 17:01:00
|
显示全部楼层
>>> print("小甲鱼","爱","编程")
小甲鱼 爱 编程
>>> def myfunc(*args):
print("有{}个参数。".format(len(args)))
print(f"有{len(args)}个参数。")
print("第2个参数是:{}".format(args[1]))
print(f"第2个参数是:{args[1]}")
>>> myfunc("小甲鱼","不二如是")
有2个参数。
有2个参数。
第2个参数是:不二如是
第2个参数是:不二如是
>>> myfunc(1,2,3,4,5)
有5个参数。
有5个参数。
第2个参数是:2
第2个参数是:2
>>> def myfunc(*args):
print(args)
>>> myfunc(1,2,3,4,5)
(1, 2, 3, 4, 5)
>>> # 元组具有打包和解包的能力
>>> #函数也可以返回多个值
>>> def myfunc():
return 1,2,3
>>> myfunc()
(1, 2, 3)
>>> x,y,z=myfunc()
>>> x
1
>>> y
2
>>> z
3
>>> 3
3
>>> # * 就是讲参数打包操作,打包到一个元组里面
>>> def myfunc(*args):
print(type(args))
>>> myfunc(1,2,3,4,5,6)
<class 'tuple'>
>>> def myfunc(*args,a,b):
print(args,a,b)
>>> myfunc(1,2,3,4,5)
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
myfunc(1,2,3,4,5)
TypeError: myfunc() missing 2 required keyword-only arguments: 'a' and 'b'
>>> *收集参数后面只能用关键字参数分配实参
SyntaxError: can't use starred expression here
>>> myfunc(1,2,3,a=4,b=5)
(1, 2, 3) 4 5
>>> def abc(a,*,b,c):
print(a,b,c)
>>> abc(1,2,3)
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
abc(1,2,3)
TypeError: abc() takes 1 positional argument but 3 were given
>>> abc(1,b=2,c=3)
1 2 3
>>> # 收集参数还可以将参数打包为字典
>>> def myfunc(**kwargs):
print(kwargs)
>>> myfunc(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
>>> def myfunc(a,*b,**c):
print(a,b,c)
>>> myfunc(1,2,3,4,a=1,b=2,c=3)
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
myfunc(1,2,3,4,a=1,b=2,c=3)
TypeError: myfunc() got multiple values for argument 'a'
>>> myfunc(1,2,3,4,x=1,y=2,z=3)
1 (2, 3, 4) {'x': 1, 'y': 2, 'z': 3}
>>> help(str.format)
Help on method_descriptor:
format(...)
S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
>>> args=(1,2,3,4)
>>> def myfunc(a,b,c,d)
SyntaxError: invalid syntax
>>> def myfunc(a,b,c,d):
print(a,b,c,d)
>>> myfunc(args)
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
myfunc(args)
TypeError: myfunc() missing 3 required positional arguments: 'b', 'c', and 'd'
>>> myfunc(*args)
1 2 3 4
>>> # 用* 来解包位置实参 ,用**来解包关键字参数
>>> kwargs={"a":1,"b":2,"c":3,"d":4}
>>> myfunc(**kwargs)
1 2 3 4
>>> |
|