Feasible in Python ? list of object , with two exeptional objects

Osiris nono at hotmail.com
Thu Dec 28 04:10:35 EST 2006


On Wed, 27 Dec 2006 16:29:29 -0600, "Paul McGuire"
<ptmcg at austin.rr._bogus_.com> wrote:

>"Osiris" <nono at hotmail.com> wrote in message 
>news:6eo5p2di7lrcs5smouhg8ju83901b4hld0 at 4ax.com...
>> Is the following intuitively feasible in Python:
>> I have an array (I come from C) of identical objects, called sections.
>> These sections have some feature, say a length, measured in mm, which
>> is calculated by a method A_length of the instantiation of the
>> Section's class.
>> Only, two elements in the array (or list ?) have a length that must be
>> calculated according to a totally different procedure, a different
>> function or method.
>> After calculation of ALL the lengths, they must be added together and
>> output.
>> The calculation procedure screams for a FOR or a WHILE loop allong the
>> list of sections, only those two sections mentioned make life
>> difficult.
>>
>
>Any reason you don't just use simple inheritance?
>
>
>from random import choice
>class BasicSection(object):
>    def __str__(self):
>        return "%s: %s" % (self.__class__.__name__, self.A_length())
>
>class OrdinarySection(BasicSection):
>    def __init__(self):
>        # boring numbers
>        self.mundaneLengthValue = choice(range(10))
>    def A_length(self):
>        return self.mundaneLengthValue
>
>class ExceptionalSection(BasicSection):
>    def __init__(self):
>        # exceptional numbers!
>        self.extraordinaryLengthValue = 
>choice([1.414,3.14159,2.71828,1.6180339,])
>    def A_length(self):
>        return self.extraordinaryLengthValue
>
># create list of Sections, randomly choosing Ordinary or Exceptional ones
>listOfSections = [ choice( (OrdinarySection,ExceptionalSection) )()
>                    for i in range(10) ]
>
># now iterate over the list and get length for each
>totalLength = 0
>for sec in listOfSections:
>    print "Adding length of " + str(sec)
>    totalLength += sec.A_length()
>print "total =", totalLength
>
># or more Pythonically, use a generator expression
>totalLength = sum( sec.A_length() for sec in listOfSections )
>print "total =", totalLength
>
>One sample run gives this result (although because we randomly choose which 
>class to create when adding elements to the list, the results are different 
>every time):
>Adding length of OrdinarySection: 6
>Adding length of OrdinarySection: 2
>Adding length of OrdinarySection: 0
>Adding length of OrdinarySection: 4
>Adding length of OrdinarySection: 1
>Adding length of ExceptionalSection: 3.14159
>Adding length of OrdinarySection: 4
>Adding length of ExceptionalSection: 3.14159
>Adding length of ExceptionalSection: 2.71828
>Adding length of ExceptionalSection: 1.414
>total = 27.41546
>total = 27.41546
>
>
>In truth, it is not even necessary for both classes to subclass from 
>BasicSubject (as would be the case in C++ or Java).  Python's duck-typing 
>will take any object that implements A_length() - I just created a common 
>superclass to put the __str__ method in, and to more classically follow 
>common inheritance patterns.
>
>-- Paul 
>

Thank you for your elaborate answer.
This indeed gives me an idea of how it would be possible.
What you say is, that I would make two entirely separate classes.
Now, the classes are going to be big: lots of methods and attributes.
A lot of the methods are going to be identical, only a few (crucial
ones) will be special.
Would I put all the stuff that is the same in both classes in the base
class and only the differing stuff in the subclasses ?
=========================
class Super:  # a big super class
    def methodA etc
    def methodX etc

class normalSection(Super): # two small subclasses
   def length etc

class SpecialSection(Super):
  def length etc.

listOfSections =
[normalSection,normalSection,specialSection,specialSection,normalSection]

for section in ListOfSections:
   total += section.length() 
   someOtherTotal += section.MethodA() 
===========================

Could I move the normal length method to the superclass, and override
it in the special class,  like this:

===========================
class Super:  # a big base class
    def methodA etc
    def methodX etc
    def length etc

class normalSection(Super): # not needed anymore

class SpecialSection(Super): # just the special stuff in here, 
  def length etc.                    # overriding the base class

listOfSections = [Super, Super, Super, SpecialSection, Super]
==================================

Some background:
Always when I dive into a new language (after Fortran, Basic, Pascal,
Forth, ASM's, C, Java(script), PHP etc.) I take a known
problem/program and try to do it in the new language, so I can
concentrate on the langiage peculiarities, and now the problem to
solve. Most languages give new ways to do thing properly. In C i did
this with arrays of function pointers, which I thought was rather
elegant. Before I start learning a new language, I want to have an
idea of how to do the special things that are needed in my problem,
rather than discovering late on the learning curve, the new language
is inappropriate... 



More information about the Python-list mailing list