【发布时间】: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