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

O

Osiris

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.

I was thinking along the line of building a class Section, instantiate
a list of objects of this class, and then replace 2 of the elements of
the list by instantiations of the special class...
Or maybe replace only the method in question by the special method...
It would be neat, if I could just walk the FOR loop, constructing the
list and calculate the total length in one go...

Concretely, the situation is a Plone site that passes user "section"
data to a Python / C server-side to do calculations on the section
data and return the result over the web.
 
M

Marc 'BlackJack' Rintsch

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.

Is this something that the instances of section "know" or is some external
"knowledge" needed to identify those special objects?
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.

Sounds like something like ``sum(section.length() for section in sections)``.

Your description is a bit vague. Where and how do you start to treat the
objects different. Is it possible to decide at instantiation time to
create a `Section` object or a `SpecialSection` object? How much
different is the calculation? Do you need two separate classes or just
one with a flag or maybe a function as argument to the `__init__()`
method? Are you writing the `Section` class(es) just for this
calculation or do they contain other behavior too?

Ciao,
Marc 'BlackJack' Rintsch
 
P

Paul McGuire

Osiris said:
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
 
O

Osiris

Is this something that the instances of section "know" or is some external
"knowledge" needed to identify those special objects?

the sections know, beforehand. I can write the method NOW.
Sounds like something like ``sum(section.length() for section in sections)``.

Your description is a bit vague. Where and how do you start to treat the
objects different.

I create all sections, also the differeent one. I know all along which
is differeent.
Is it possible to decide at instantiation time to
create a `Section` object or a `SpecialSection` object? How much
YES

different is the calculation?

rather al lot.
Do you need two separate classes or just
one with a flag or maybe a function as argument to the `__init__()`

is differenter than that..
method? Are you writing the `Section` class(es) just for this
calculation or do they contain other behavior too?

They have a lot of other behavior too...
 
O

Osiris

Osiris said:
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...
 
M

Marc 'BlackJack' Rintsch

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 ?

Yes that's the intent of base/sub class relationships. Baseclasses
contain the behavior common to all their subclasses and subclasses
implement just the different or additional behavior.
Could I move the normal length method to the superclass, and override
it in the special class, like this:

Yes that can be done and makes perfectly sense if the `length()` in the
baseclass is the "normal" behavior and that baseclass can be instantiated
and used directly.

Ciao,
Marc 'BlackJack' Rintsch
 
O

Osiris

Yes that's the intent of base/sub class relationships. Baseclasses
contain the behavior common to all their subclasses and subclasses
implement just the different or additional behavior.


Yes that can be done and makes perfectly sense if the `length()` in the
baseclass is the "normal" behavior and that baseclass can be instantiated
and used directly.

Ciao,
Marc 'BlackJack' Rintsch


now we're rolling ! :)
thnx both.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top