I have two classes - one that inherits from the other. I want to know how to cast (or create a new variable) a subclass. I searched a bit and mostly “depressing” as if it were being deprecated, and there are some tricky workarounds, such as setting up an instance. class - although this doesn't seem like a good way.
eg. http://www.gossamer-threads.com/lists/python/python/871571 http://code.activestate.com/lists/python-list/311043/
to the question - is despondency really so bad? If so, why?
Below I simplified the code example - basically I have some code that creates a Peak object after some analysis of the x, y data. outside this code, I know that the data has a “PSD” data power spectral density, so they have some additional attributes. How do I cast from peak to 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
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)
p = peakfind(np.random.rand(10),np.random.rand(10))
p_psd = ????????????
edit
Thanks for the contribution .... I'm afraid I felt rather sad (geddit?), Since the answers so far seem to suggest that I spend time hard programming the converters from one type of class to another. I came up with a more automatic way to do this - basically sorting through class attributes and passing them to each other. how does it smell for people - is it wise to do this - or is it creating problems?
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():
setattr(descendent, name, value)
return descendent