How do I go down in python

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 # 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 = ????????????

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():
        #print "setting descendent", name, ": ", value, "ancestor", name
        setattr(descendent, name, value)

    return descendent
+6
source share
3 answers

"" Python. - , , . , , __init__ (, , ).

, __class__ , . , - "", , , , .

Python. ( : , . : Python , , .) , , , , .

+8

(IMHO). peekfind() Peak - , Psd_Peak, Psd_Peak. - ++ , , - ++, Psd_Peak . python , (fred = fred, jane = jane) .

factory Peak, peekfind(), .

def peak_factory(peak_type, index, *args, **kw):
    """Create Peak objects

    peak_type     Type of peak object wanted
       (you could list types)
    index         index
       (you could list params for the various types)
    """
    # optionally sanity check parameters here
    # create object of desired type and return
    return peak_type(index, *args, **kw)

def peakfind(peak_type, xdata, ydata, **kw) :
    # do some stuff...
    return peak_factory(peak_type, 
         1,
         0,
         1,
         .5,
         10,
         **kw)

# Find a peak in the data.
p = peakfind(Psd_Peak, np.random.rand(10), np.random.rand(10), depth=111, ampest=222)
+1

See the following example. Also be sure to follow the LSP (Liskov Substitution Principle)

class ToBeCastedObj:
    def __init__(self, *args, **kwargs):
        pass  # whatever you want to state

    # original methods
    # ...


class CastedObj(ToBeCastedObj):
    def __init__(self, *args, **kwargs):
        pass  # whatever you want to state

    @classmethod
    def cast(cls, to_be_casted_obj):
        casted_obj = cls()
        casted_obj.__dict__ = to_be_casted_obj.__dict__
        return casted_obj

    # new methods you want to add
    # ...
0
source

All Articles