Skip to main content
 首页 » 编程设计

python之在 Python 中获取第一个和最后一个函数参数

2025年05月04日14wuhuacong

我必须在 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] 

请您参考如下方法:

还有一种方法可以在 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]]