Python - args 和 **kargs

Python - args an **kargs

我有这个全局 function:

def filterBelowThreshold(name, feature, tids, xsongs, **kwargs):
    print (name, 'PLAYLIST')
    for i, x in enumerate(feature):
        if x < value:
            track_name = sp.track(tids[i])['name']
            xsongs.append(track_name)
            print(name, ":", "{} - feature: {}".format(track_name, x))

我想在 class function 中调用它,传递以下参数(其变量在本地声明):

filterBelowThreshold('myname', energy, tids, xsongs, value=0.650)

class function 函数调用之前,我声明了以下变量:

energy = [item 1, item2, item3, ...]

tids = []

xsongs = []

GLOBAL 函数的正确语法是什么?

test.py

def filterBelowThreshold(name, feature, tids, xsongs, **kwargs):
    print kwargs['value']

class Test(object):
    def __init__(self):
        energy = ['item 1', 'item2', 'item3' ]
        tids = []
        xsongs = []
        filterBelowThreshold('myname', energy, tids, xsongs, value=0.650)

a = Test()

python test.py 将打印 0.65

你已经定义好了,没有问题。您面临的问题是什么?

如果使用显式参数 value 调用函数,则不应使用 **kwargs,只需使用普通参数:

def filterBelowThreshold(name, feature, tids, xsongs, value):
    print(name, 'PLAYLIST')
    for tid, x in zip(tids, feature):
        if x < value:
            track_name = sp.track(tid)['name']
            xsongs.append(track_name)
            print("{} : {} - feature: {}".format(name, track_name, x))

并这样称呼它

filterBelowThreshold('myname', energy, tids, xsongs, value=0.650)

filterBelowThreshold('myname', energy, tids, xsongs, 0.650)