2015-04-04 42 views
1

我必須在Python中創建一個包含兩個以上參數的函數,最後我必須打印該函數的第一個和最後一個參數(在列表中)。在Python中獲取第一個和最後一個函數參數

我試過這樣,但它不起作用。我究竟做錯了什麼?

import inspect 

def func(a, b, c): 
    frame = inspect.currentframe() 
    args, _, _, values = inspect.getargvalues(frame) 
    for i in args: 
     return [(i, values[i]) for i=0 and i=n] 

回答

3

還有一個辦法讓蟒蛇可變數量的函數參數(這就是所謂的var-positional)。然後他們結束列表:

def func(*args): # The trick here is the use of the star 
    if len(args) < 3: # In case needed, also protects against IndexError 
     raise TypeError("func takes at least 3 arguments") 
    return [args[0], args[-1]] 
+0

非常感謝。這就是我一直在尋找的東西。 – Eleanordum 2015-04-04 11:38:38

3

你正在推翻這一點。你已經有了第一個和最後的論點引用:

def func(a, b, c): 
    print [a, c] 
+0

我認爲這太簡單了。謝謝! – Eleanordum 2015-04-04 11:13:47

相關問題