Python 定义外部函数中嵌套函数的参数

2024-04-25 06:46:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下功能:

def splot (self,what):
    df = pd.DataFrame((self.spec[what]).compute()).plot()
    plt.show()
    return df

我希望在调用splot函数时能够将parameters传递给.plot()方法,如下所示:

def splot (self,what,arg=None):
    df = pd.DataFrame((self.spec[what]).compute()).plot(arg)
    plt.show()
    return df

所以当我调用splot时,我给它两个参数:'what'(一个字符串),以及我希望plot命令采用的参数。你知道吗

但是,这不起作用:如果我将参数作为字符串传递,我将得到一个KeyError,如果不是,它将抛出一个变量错误。我有一种感觉*args应该涉及到某个地方,但不知道如何在这个例子中使用它。你知道吗


Tags: selfdataframedf参数returnplotdefshow
1条回答
网友
1楼 · 发布于 2024-04-25 06:46:52

实际上,正如您所猜测的,您必须使用unpacking操作符*。下面是一个与您相近的代码示例,以解释:

class myClass:

    def myPlot(self, x=None, y=None):
        print("myPlot:", x)
        print("myPlot:", y)

    def myFunc(self, what, *args, **kwargs):
        print(what)         # 'toto'
        print(args)         # tuple with unnamed (positional) parameters
        print(kwargs)       # dictionary with named (keyword) parameters
        self.myPlot(*args, **kwargs)   # use of * to unpack tuple and ** to unpack dictionary


myObject = myClass()
myObject.myFunc("toto", 4, 12)         # with positional arguments only
myObject.myFunc("toto", x = 4, y = 12) # with keyword arguments only
myObject.myFunc("toto", 4, y = 12)     # with both

所以你应该这样写你的代码:

def splot (self, what, *args, **kwargs):
    df = pd.DataFrame((self.spec[what]).compute()).plot(*args, **kwargs)
    plt.show()
    return df

相关问题 更多 >