【问题标题】:Inheriting Attributes from Classes in Python从 Python 中的类继承属性
【发布时间】:2015-06-23 16:30:25
【问题描述】:

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

AttributeError: type object 'dataClass' has no attribute 'name'

如何让 _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')

【问题讨论】:

  • 这是一个很奇怪的代码。不知道它应该做什么,很难提供帮助。
  • 它将以不同方式处理的望远镜数据存储为对象的模型。当我想用不同的数据制作大图时,object._plot 函数可以(如果传递一个数字)将自己添加到图中
  • 您有两个相关的类,业务逻辑分布在它们之间。请展示您如何创建类实例以及如何调用导致异常的方法。此外,{'model': 'Thermal Conductivity'}setattr(self, model_name, _model(model_name)) 意味着您将拥有名称为 'Thermal Conductivity' 的属性,您将无法正常访问该属性。最后一行的test._plot 是什么?
  • 我更新了代码以更能代表我所写的内容
  • super(_model,self).__init__(...)这一行应该在_model.__init__,但我不确定从dataClass继承_model是否正确

标签: python inheritance parent-child subclass super


【解决方案1】:

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

name = dataClass.name

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

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

这里你已经创建了实例属性,如果你有实例,你可以访问它。

如何让 _plot 继承 dataClass 的 .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__()

您正在从非构造函数方法调用父类“构造函数”。

【讨论】:

  • 是的,'name = self.name' 不起作用。新的错误消息是 AttributeError: '_model' object has no attribute 'name'
【解决方案2】:

您可以尝试做两件事(据我所知)。您可能正在尝试访问类属性,或者您正在尝试访问实例属性。如果你想要第一个,你需要你的 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" 访问它,其中模型名称是您要访问的模型的名称.

如果您尝试访问实例属性,则必须将 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)

希望这会更有用。

【讨论】:

  • 它将以不同方式处理的望远镜数据存储为对象模型。当我想用不同的数据制作大图时,object._plot 函数可以(如果传递一个图)将自己添加到现有图
  • 您是否尝试拥有 dataClass 对象的单个实例,并让所有 _model 对象访问它?
  • 它将以不同方式处理的望远镜数据存储为对象模型。当我想用不同的数据制作大图时,object._plot 函数可以(如果传递一个数字)将自己添加到现有的图中。对于情节标题,我需要对象的名称;但是名称不存储为 object.model.nameobject.name 我无法获取绘图函数来访问 object.name
  • 就功能而言,我了解您的意图。我在问如何你想实现它。您想要 dataClass 对象的单个实例吗?这意味着,您是否要将所有模型存储在该数据类中?我不认为继承是你想要用于这项工作的。
  • 我做了类似 'Dust = dataClass('Dust', {'model': 'raw', 'data': [eqn.dustRatio(const)*eqn.dust(l) for l在 lDict['lList']]}); Dust.add_model({'model': 'bin', 'data': fn.binData(Dust.raw.data, lDict['lList'])})' 以及一大堆其他的东西,比如 Dust 然后我想为每个对象绘制所有原始数据模型,所以我制作一个图形,然后使用 for 循环将图形传递给每个对象的“_plot”,然后它们将自己添加到图形中,然后我结束完成一个情节。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 2011-04-10
  • 2021-01-25
  • 2012-07-25
  • 2011-01-30
  • 2016-11-11
相关资源
最近更新 更多