获取Python中的第一个和最后一个函数参数

时间:2015-04-04 11:08:47

标签: python function arguments

我必须在python中创建一个包含2个以上参数的函数,最后我必须打印函数的第一个和最后一个参数(在列表中)。

我试过这样,但它不起作用。我做错了什么?

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]

2 个答案:

答案 0 :(得分:3)

你正在思考这个问题。您已经引用了第一个和最后一个参数:

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

答案 1 :(得分:3)

还有一种方法可以在python中获取可变数量的函数参数(它被称为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]]