在Python中继承类中的属性

时间:2015-06-23 16:30:25

标签: python inheritance parent-child subclass super

我需要 _plot 函数才能访问 dataClass .name 属性,以便图表具有标题。但是,我一直收到错误:

AttributeError:type object' dataClass'没有属性'名称'

如何让_plot继承 dataClass .name 属性?

import matplotlib.pyplot as plt.

class dataClass(object):
    def __init__(self, name, dictionary):
        self.name = name
        self.add_model(dictionary)
    def add_model(self, dictionary):
        model_name = dictionary['model']
        setattr(self, model_name, _model(model_name)
        *there is some code here which gives real vales to model.data, model.error, and model.xaxis*

class _model(dataClass):
    def __init__(self, model_name):
        self.modelname = model_name
        self.data = None
        self.error = None
        self.xaxis = None

    def _plot(self, fig=None, ax=111, xaxis=None, **kwargs):
        if fig is None:                     # no figure given
            fig = plt.figure()
            ax = plt.subplot(ax)
        elif isinstance(ax, (int, float)):  # figure given
            ax = fig.add_subplot(ax)
        else:                               # figure and axis given
            pass
        if xaxis is None:
            xaxis = self.xaxis
        super(_model,self).__init__   # this line doesn't work
        name = dataClass.name         # this line raises the error
        name = ax.errorbar(xaxis, self.data, yerr=self.error, ls='-', label=name)
        handles, labels = ax.get_legend_handles_labels()
        ax.legend(handles, labels, loc='upper right')
        return fig

def makePlot(xAxis, thing_to_plot):
    fig, ax = plt.subplots(1, 1)
    thing_to_plot._plot(fig, ax, xAxis)
    plt.title("Measured and Best Fit Function")
    plt.savefig("lineplots2.png")
    plt.close(fig)

Dust = dataClass('Dust', {'model': 'raw', 'data': [eqn.dustRatio(const)*eqn.dust(l) for l in lDict['lList']]})
makePlot(lDict['lList'], Dust.raw)

提前致谢。

修改 我在Stack Overflow的其他地方发现了一个帖子,它提供了一些关于如何使对象添加到现有图中的建议。我拿了代码并编辑了它。现在我试图让这个练习功能成为我实际代码的一部分

class Plotter(object):
    def __init__(self, xval=None, yval=None):
        self.xval = xval
        self.yval = yval
        self.error = None

    def plotthing(self, fig=None, index=1):
        if fig is None:
            fig = plt.figure()
            ax = plt.subplot(111)
        else:
            ax = fig.add_subplot(2,1,index)
        name = 'curve{}'.format(1)
        name = ax.errorbar(self.xval, self.yval, yerr=self.error, ls='-', label=name)
        handles, labels = ax.get_legend_handles_labels()
        ax.legend(handles, labels, loc='upper right')
        return fig


def compareplots(*args):
    fig = plt.figure()
    for i, val in enumerate(args):
        val.plotthing(fig, i+1)
        plt.title("Measured and Best Fit Function")
    return fig

app1 = Plotter(xval=range(0,10), yval=range(0,10))
plot1 = app1.plotthing()
plot1.savefig('testlong.png')
app2 = Plotter(xval=range(0,11), yval=range(1,12))

thingummy = compareplots(app1, app2)
thingummy.savefig('test.png')

2 个答案:

答案 0 :(得分:0)

我猜这个异常发生在这一行:

name = dataClass.name

在这里,您尝试访问不存在的类dataClass的类属性:

class dataClass(object):
    def __init__(self, name, dictionary):
        self.name = name
        self.add_model(dictionary)

此处您已创建了实例属性,如果您拥有该实例,则可以访问该属性。

  

如何让_plot继承dataClass' s .name属性?

_model类实例自动继承此属性。 我想你的意思是使用name = self.name代替name = dataClass.name,但这让我有疑问:

def _plot(self, fig=None, ax=111, xaxis=None, **kwargs):
    if fig is None:
        fig = plt.figure()
    super(_model,self).__init__()

您正在呼叫父类"构造函数"来自非构造方法。

答案 1 :(得分:0)

您可能尝试做两件事(我知道)。您可能正在尝试访问类属性,或者您正在尝试访问实例属性。如果你想要第一个,你需要你的dataClass:

class dataClass(object):
    name = 'jim'
    def __init__(self, dictionary):
        self.add_model(dictionary)
    def add_model(self, dictionary):
        model_name = dictionary['model']
        setattr(self, model_name, _model(model_name))

如果您尝试访问add_model方法中setattr()分配的类属性,则必须使用dataClass访问它。“model_name”其中model name是您要访问的模型的名称

如果您尝试访问实例属性,则必须将dataClass对象的实例传递给方法的_model,或者执行类似的操作。程序的整体结构非常混乱,因为我不确定通过这种方式访问​​属性以及将属性添加到dataClass对象的方式来实现目标。

如果您只想继承class属性,那么您只需要使用上面的代码。我不确定你的继承是什么意思,因为它似乎并不像你所追求的那样继承。如果你能澄清你的意图,那将是非常有益的。

修改 在更好地了解了您要做的事情之后,我认为更好的方法是访问这些信息,就像这样的类:

class dataClass(object):
    def __init__(self, name, dictionary):
        self.name = name
        self.models = {}
        self.add_model(dictionary)

    def add_model(self, dictionary):
        model_name = dictionary['model']
        if 'data' in dictionary:
            data = dictionary['data']
        else:
            data = None
        self.models.update({model_name : data})

class model(object):
    def __init__(self, model_name):
        self.modelname = model_name

    def plot(self, thing_to_plot , fig=None, ax=111, xaxis=None, **kwargs):
        # do meaningful work here
        return thing_to_plot.name

example = dataClass('Aluminum', {'model': 'Thermal Conductivity'})
thing = model("doug")

print("Plotted object's name: %s" % thing.plot(example))
print("_model name: %s" % thing.modelname)

希望这会更有用。