python中可选参数是什么意思_尝试理解Python中的可选参数、列表参数和命名参数...

我是Python的初学者,试图理解函数参数及其类型和顺序。在

我试着用不同的论点做一个小实验,这是我的实验def main():

test_a(2, 33, 44)

test_b(2, 33)

test_c(2)

## test_d(2,,44) **Produces Invalid syntax**

test_e(2,33,44,55,66)

test_f(2, 44,55,66, y = 44)

test_g(2, 33, 44,55,66, rofa = 777, nard = 888)

##test_h(2, 33, foo = 777, boo = 888, 44,55,66) **Invalid Syntax in Function definition

##test_l(2, 44,55,66 , foo= 777, boo = 888, y = 900) **Invalid Syntax in Function definition

test_m(2, 44,55,66 , y = 900, foo=77777 , boo = 88888)

#############################################################

## NO optional arguments

def test_a(x,y,z):

print("test_a : x = {}, y = {}, z = {} ".format(x ,y ,z))

## One optional argument at the end

def test_b(x, y, z = 22):

print("test_b : x = {}, y = {}, z = {} ".format(x ,y ,z))

## TWO optional arguments at the end

def test_c(x, y = 11, z = 22):

print("test_c : x = {}, y = {}, z = {} ".format(x ,y ,z))

## ONE optional argument at the middle

## Produces Non-default argument follows default argument

#### **** DEFAULT ARGUMENTS MUST COME AT THE END **** ####

## def test_d(x, y = 11, z):

## print("test_d : x = {}, y = {}, z = {} ".format(x ,y ,z))

#################################################################

## NO optional argument + One List argument

def test_e(x, y, *args):

print("test_e : x = {}, y = {} ||".format(x, y), end= " ")

for i in args :

print(i)

## One optional argument + One list argument

def test_f(x, *args , y = 5):

print("test_f : x = {}, y = {} ||".format(x, y), end= " ")

for i in args :

print(i)

################################################################

## No optional argument, one list, one keyword arguments

def test_g(x,y,*args, **kwargs):

print(x, y)

for i in args:

print(i)

for i, v in kwargs.items():

print(i, v)

## **kwargs befor *args produces syntax error !!!

##def test_h(x,y, **kwargs, *args):

## print(x, y)

## for i in args:

## print(i)

##

## for i, v in kwargs.items():

## print(i, v)

## **kwargs befor optional argument produces syntax error !!!

##def test_l(x,*args,**kwargs, y = 5):

## print(x, y)

## for i in args:

## print(i)

##

## for i, v in kwargs.items():

## print(i, v)

##

## One optiona, list and keyword arguments

def test_m(x,*args,y = 5, **kwargs):

print(x, y)

for i in args:

print(i)

for i, v in kwargs.items():

print(i, v)

if __name__ == "__main__":

main()

经过这次实验,我真的理解了大部分事情。但有一个问题我无法理解。在

在test_h和test_m中的函数定义中,**kwargs在可选参数和列表参数之前定义,当我运行程序时,即使我没有使用该函数,也只是定义了它。。它产生Syntax Error。。我很高兴知道为什么会这样?在

谢谢。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值