python函数参数中单独的*的含义

函数中形参列表出现一个单独的*,如下所示:

test_func2(aa, *, bb, cc='hello'): 这表示*号后面的形参只能以关键字形式进行传参,不接受位置传参
就只能接受 bb='xxx', cc='xxx', 不能接受其他的命名关键字参数了

def test_func1(aa, bb, cc='hello'):
print('11111 ', aa)
print('22222 ', bb)
print('33333 ', cc)
def test_func2(aa, *, bb, cc='hello'):
print('11111 ', aa)
print('22222 ', bb)
print('33333 ', cc)
test_func1('haha', 'hehe', 'heihei')
11111 haha
22222 hehe
33333 heihei
test_func2('haha', 'hehe', 'heihei')
Traceback (most recent call last):
File "<ipython-input-5-ec0696934d76>", line 1, in <module>
test_func2('haha', 'hehe', 'heihei')
TypeError: test_func2() takes 1 positional argument but 3 were given
test_func2('haha', bb='hehe')
11111 haha
22222 hehe
33333 hello
test_func2('haha', bb='hehe', cc='heihei')
11111 haha
22222 hehe
33333 heihei

参考链接

posted @   rain-1227  阅读(418)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!
点击右上角即可分享
微信分享提示