我有两个类 - 一个继承自另一个。我想知道如何转换(或创建一个新变量)子类。我已经搜索了一下,而且大多数情况下像这样的“垂头丧气”似乎是不受欢迎的,并且有一些稍微狡猾的解决方法,比如设置实例。类- 虽然这似乎不是一个好方法。
例如。 http://www.gossamer-threads.com/lists/python/python/871571 http://code.activestate.com/lists/python-list/311043/
子问题 - 垂头丧气真的那么糟糕吗?如果是,为什么?
我在下面简化了代码示例 - 基本上我有一些代码在对 x、y 数据进行了一些分析后创建了一个 Peak 对象。在这段代码之外,我知道数据是“PSD”数据功率谱密度——所以它有一些额外的属性。我如何从 Peak 向下投射到 Psd_Peak?
"""
Two classes
"""
import numpy as np
class Peak(object) :
"""
Object for holding information about a peak
"""
def __init__(self,
index,
xlowerbound = None,
xupperbound = None,
xvalue= None,
yvalue= None
):
self.index = index # peak index is index of x and y value in psd_array
self.xlowerbound = xlowerbound
self.xupperbound = xupperbound
self.xvalue = xvalue
self.yvalue = yvalue
class Psd_Peak(Peak) :
"""
Object for holding information about a peak in psd spectrum
Holds a few other values over and above the Peak object.
"""
def __init__(self,
index,
xlowerbound = None,
xupperbound = None,
xvalue= None,
yvalue= None,
depth = None,
ampest = None
):
super(Psd_Peak, self).__init__(index,
xlowerbound,
xupperbound,
xvalue,
yvalue)
self.depth = depth
self.ampest = ampest
self.depthresidual = None
self.depthrsquared = None
def peakfind(xdata,ydata) :
'''
Does some stuff.... returns a peak.
'''
return Peak(1,
0,
1,
.5,
10)
# Find a peak in the data.
p = peakfind(np.random.rand(10),np.random.rand(10))
# Actually the data i used was PSD -
# so I want to add some more values tot he object
p_psd = ????????????
编辑
感谢您的贡献....恐怕我感到相当沮丧(geddit?),因为到目前为止的答案似乎表明我花时间从一种类类型到另一种类类型的硬编码转换器。我想出了一种更自动化的方法——基本上循环遍历类的属性并将它们相互转移。这种气味对人们有什么影响——这样做是否合理——或者它会给未来带来麻烦?
def downcast_convert(ancestor, descendent):
"""
automatic downcast conversion.....
(NOTE - not type-safe -
if ancestor isn't a super class of descendent, it may well break)
"""
for name, value in vars(ancestor).iteritems():
#print "setting descendent", name, ": ", value, "ancestor", name
setattr(descendent, name, value)
return descendent