从Python中的类继承属性

从Python中的类继承属性,python,inheritance,parent-child,subclass,super,Python,Inheritance,Parent Child,Subclass,Super,我需要_plot函数能够访问dataClass的.name属性,以便图形具有标题。然而,我不断得到错误: AttributeError:类型对象“dataClass”没有属性“name” 如何获取_plot以继承dataClass的.name属性 import matplotlib.pyplot as plt. class dataClass(object): def __init__(self, name, dictionary): self.name = name

我需要_plot函数能够访问dataClass的.name属性,以便图形具有标题。然而,我不断得到错误:

AttributeError:类型对象“dataClass”没有属性“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)
提前谢谢

编辑 我在别处找到了一篇关于堆栈溢出的帖子,它给出了一些建议,说明了如何让对象将自己添加到现有的绘图中。我把代码编辑成这个。现在,我正试图使这个练习函数成为我实际代码的一部分

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')

我猜这一行会出现异常:

name = dataClass.name
在这里,您试图访问不存在的class
dataClass
的class属性:

class dataClass(object):
    def __init__(self, name, dictionary):
        self.name = name
        self.add_model(dictionary)
在这里,您已经创建了实例属性,如果您有实例,您可以访问该属性

如何获取_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)
\u 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__()
您正在从非构造函数方法调用父类“构造函数”。

您可以尝试做两件事(据我所知)。您可以尝试访问类属性,也可以尝试访问实例属性。如果您想要第一个,您需要的数据类如下所示:

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))
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)
如果试图访问由add_model方法中的setattr()指定的类属性,则必须使用dataClass.“model_name”来访问该属性,其中model name是要访问的模型的名称

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

如果您只想继承class属性,那么只需要使用上面的代码。我不确定你所说的继承到底是什么意思,因为看起来继承并不是你真正想要的。如果你能澄清你的意图,那将是非常有益的

编辑: 在更好地了解您要做的事情之后,我认为访问这些信息的更好方法是使用以下类:

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))
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.\u plot函数可以(如果传递了一个图形)将自己添加到绘图中。您有两个相关的类,它们之间有业务逻辑。请说明如何创建类实例以及如何调用导致异常的方法。另外,
{'model':'Thermal Conductivity'}
以及
setattr(self,model\u name,\u model(model\u name))
意味着您将拥有名为
'Thermal Conductivity'
的属性,您将无法正常访问该属性。那是什么
测试.\u在最后一行绘制了
?我更新了代码,使之更能代表我所写的
super(\u model,self)。\uu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,“name=self.name”不起作用。新的错误消息是AttributeError:“\u model”对象没有属性“name”。它将以不同方式处理的望远镜数据存储为对象的模型。当我想用不同的数据块绘制大型绘图时,object.\u plot函数可以(如果传递了一个图形)将自己添加到现有的绘图中。您是否尝试使用dataClass对象的单个实例,并让所有的\u model对象访问它?它将以不同方式处理的望远镜数据存储为对象的模型。当我想用不同的数据块绘制大型绘图时,object.\u plot函数可以(如果传递了图形)将其自身添加到现有绘图中。对于情节标题,我需要对象的名称;但是,名称不是存储为object.model.name,而是存储为object.name。我无法使用绘图函数访问object.name。就功能而言,我了解您的意图。我是问你想如何实现它。是否需要dataClass对象的单个实例?这意味着,您要在该数据类中存储所有模型吗?我不认为继承是您希望用于此工作的内容。我制作了类似于'Dust=dataClass('Dust',{'model':'raw','data':[eqn.dustRatio(const)*eqn.Dust(l)的东西,用于lDict['lList']}中的l;add_model({'model':'bin','data':fn.binData(Dust.raw.data,lDict['lList']))还有一大堆其他的东西,比如灰尘,然后我想绘制每个对象的所有原始数据模型,所以我做了一个图,然后使用for循环将图通过每个对象的“u图”,它们将自己添加到图中,最后我得到了一个完成的图。