如何将 (*args,**kwargs) 类型的属性传递给 class 内的函数?

How to pass a (*args,**kwargs) type of attribute to a function within class?

我想为我的科学数据的自定义绘图创建一个模块,但我不知道如何将 (*arg2,**kwarg2) 类型的参数传递给方法。

相关代码如下:

import numpy as np
import matplotlib.pyplot as plt

# class of figures for channel flow
# with one subfigure

class Homfig:

    # *args: list of plot features for ax1.plot
    #     (xdata,ydata,str linetype,str label)
    # **kwargs: list of axes features for ax1.set_$(STH)
    #     possible keys:
    #     title,xlabel,ylabel,xlim,ylim,xscale,yscale

    def __init__(self,*args,**kwargs):
        self.args = args
        self.kwargs = kwargs
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

        for key, val in self.kwargs.iteritems():
            getattr(self.ax,'set_'+key)(val)

    def hdraw(self):
        for arg in self.args:
            self.ax.plot(*arg)
            leg = self.ax.legend(loc=4)

问题是 arg 本身就是一个像 (*agr2,**kwarg2) 这样的元组,当我调用 self.ax.plot(*arg) 它看不到命名变量。 函数 hdraw 应该对从 init 在 *args 中获得的输入进行操作,并且绘图线的数据在 arg 中传递。 我如何表达 arg 由未命名和命名变量组成? self.ax.plot 可能会被调用多次,当我想要多行时(在一个图中有不同的 labellinetype 等。)

我从其他 python 脚本调用模块:

meanfig = hfig.Homfig((datax,datay),title='test plot')
meanfig.hdraw()

如何向 self.ax.plot 添加标签或线型等功能,例如:

meanfig = hfig.Homfig((datax,datay,label="test_label",linetype ='o'),title='test plot')

您应该可以使用双 ** 传递它们,即

def hdraw(self):
    self.ax.plot(*self.args, **self.kwargs)
    leg = self.ax.legend(loc=4)

然后使用

调用它
meanfig = hfig.Homfig(datax, datay, label="test_label", linetype ='o', title='test plot')

根据评论更新:

如果你想在同一张图中绘制多个图,你写的方式会很难,但你可以这样做

class Homfig:
    def __init__(self, title):
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

        self.args = []
        self.kwargs = []

    def add_plot(self, *args, **kwargs):
        self.args.append(args)
        self.kwargs.append(kwargs)

    def hdraw(self):
        for args, kwargs in zip(self.args, self.kwargs):
            self.ax.plot(*args, **kwargs)
        leg = self.ax.legend(loc=4)

然后使用

调用它
meanfig = hfig.Homfig(title='test plot')
meanfig.add_plot(datax, datay, label="test_label", linetype ='o')
meanfig.add_plot(datax, 2 * datay, label="test_label_2", linetype ='o')
meanfig.hdraw()