*已编辑
我想要的是如下
def func(x1, x2, ... , xi, ..., xn):
doing something
return
def F(func, i):
def newFunc(xi, x2, ..., x1, ..., xn):
return func(x1, x2, ..., xi, ..., xn)
doing something with newFunc
其中n是未知的(任意) *
我的英语不好,并且是python的初学者,所以请理解。
我制作了一个带有一个函数和一个整数的函数。
让我将函数称为F
,将F
的参数称为func
,将整数称为i
。
在F
中,创建了一个新功能,该功能切换了i
的第一个参数和第func
个参数。 (我将使用F
中的新功能来做一些事情。)
如果我确切知道func
的参数,则可以按如下所示制作F
。
但是,如果我不知道参数的数量,该如何设置F
?
def F(func, i=1):
def newFunc(u, x, e):
return func(x, u, e)
...Do something with newFunction...
我尝试了signature
,但无法切换signature
的返回。
我尝试了.__code__.co_varnames
,如下所示
def F(func, i):
arg_num = func.__code__.co_argcount
arg_pre = list(func.__code__.co_varnames)[:arg_num]
arg_next = list(func.__code__.co_varnames)[:arg_num]
arg_next[0], arg_next[i] = arg_next[i], arg_next[0]
def newFunc(arg_next):
return func(arg_pre)
但是,在这种情况下,return func(arg_pre)
将arg_pre
识别为1个位置参数。
希望您能理解我的意思。谢谢。
答案 0 :(得分:1)
@Parameters
可以接受任意数量的 个参数,尽管这意味着Phone for iPhone test is: Iphone
Phone for Samsung test is: Samsung
无法验证是否确实有{em> 是一个newFunc
调用F
的返回值时的第th个参数。
i