Python:函数最多接受4个参数(给定5个)

2024-10-01 13:39:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python的功能如下:

def PlotCurve(SourceClipName,mode,TestDetails,savepath='../captures/',**args):

    curves=[]
    for a in range(0,len(args)):
        y=[]
        for testrates in TestDetails.BitratesInTest:

            stub = args[a].Directory[testrates]
            y.append(args[a].dataset[stub][0])
            curves.append(y)

    plt.figure()
    plt.xlabel("Bitrate")
    plt.ylabel(mode)
    plt.title(TestDetails.HDorSD+" "+TestDetails.Codec + " " + SourceClipName[:-4])
    colour=["green","red","brown","orange","purple","grey","black","yellow","white",]
    CurveIDs=[]
    for x in args:
        CurveIDs.append(args.ID)
    p=[]    
    for b in range(0,len(args)-1):
        p[b].plot(TestDetails.BitratesInTest,y[b],c=colour[b])

    plt.legend((p),(CurveIDs),prop={"size":8})
    plt.savefig(os.path.join(savepath,mode+"_"+TestDetails.codec+"_"+SourceClipName[:-4]+".png"))

具体的错误是

^{pr2}$

**args是传递到函数中的对象列表

在我看来,我已经定义了一个接受5个或更多参数的函数(不管它是否正常工作),但是程序不同意,我缺少了什么使函数认为它最多只能有4个参数?在


Tags: 函数inforlenmodeargsrangeplt
3条回答

使用*args,而不是**kwargs(或**anything),调用带有参数名的函数。这将产生一个溢出参数的可变列表,然后可以像这样迭代以提取id。在

参数必须通过名称指定才能应用于**kwargs,而不是参数计数。在


*args and **kwargs?

You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function .. Similarly, **kwargs allows you to handle named arguments that you have not defined in advance.

当你说,**args is a list of objects that has been passed into the function,那么它是单*

当您将**args作为参数之一定义函数时,当您传递键值对时,它将无法解压缩

**kwargs要映射到dictionary

*args要映射到list

或者你可以两者兼得

>>> def func(argone, *args, **kwargs):
>>>    # do stuff
>>>
>>> func(1, *[1, 2, 3, 4])
>>> func(1, *[1, 2, 3, 4], **{'a': 1, 'b': 2})
>>>

很可能您是双重键入*,因为命名可选位置参数的方便性是*args,而可选命名参数是**kwargs。在

所以您的函数实际上接受4个位置参数和任意数量的keyword arguments。如果你这样称呼它:

PlotCurve(1,2,3,4,5) # you should get error
PlotCurve(1,2,3,4,aaa=5) # you should have args = {'aaa': 5}

要解决这个问题,很可能需要移除第二颗星星。在

相关问题 更多 >