2016-08-12 16 views
0

我有這個全球function的Python - ARG遊戲的** kargs

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)) 

我想叫它classfunction內通過以下參數(其變量是在本地聲明):

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

class function之內,在函數調用之前,我聲明瞭以下變量:

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

tids = []

xsongs = []

什麼是全局函數的語法正確?

+1

代碼看起來正確。我真的沒有看到任何問題... – refi64

+0

請顯示您正在嘗試寫入的課程。我無法理解你目前的嘗試。 (至於'kwargs'處理,如果它有幫助,它的工作原理是這樣的:將'value = 0.650'傳遞給'filterBelowThreshold'將使'kwargs'成爲一個'dict',只有一個鍵'value',它的值是'0.650')。 – pistache

回答

0

你不應該,如果你調用一個明確的參數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) 
0

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

您已經定義是正確的,是沒有問題的。你面臨的問題是什麼?