473,399 Members | 2,774 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

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

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.
Dec 27 '06 #1
6 1299
In <6e********************************@4ax.com>, Osiris wrote:
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
Dec 27 '06 #2
"Osiris" <no**@hotmail.comwrote in message
news:6e********************************@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
Dec 27 '06 #3
On Wed, 27 Dec 2006 23:27:08 +0100, Marc 'BlackJack' Rintsch
<bj****@gmx.netwrote:
>In <6e********************************@4ax.com>, Osiris wrote:
>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?
the sections know, beforehand. I can write the method NOW.
>
>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.
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...
>Ciao,
Marc 'BlackJack' Rintsch
Dec 28 '06 #4
On Wed, 27 Dec 2006 16:29:29 -0600, "Paul McGuire"
<pt***@austin.rr._bogus_.comwrote:
>"Osiris" <no**@hotmail.comwrote in message
news:6e********************************@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,special Section,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...
Dec 28 '06 #5
In <8v********************************@4ax.com>, Osiris wrote:
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
Dec 28 '06 #6
On Thu, 28 Dec 2006 11:14:27 +0100, Marc 'BlackJack' Rintsch
<bj****@gmx.netwrote:
>In <8v********************************@4ax.com>, Osiris wrote:
>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

now we're rolling ! :-)
thnx both.
Dec 28 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Haoyu Zhang | last post by:
Dear Friends, Python assignment is a reference assignment. However, I really can't explain the difference in the following example. When the object is a list, the assignment seems to be a...
10
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.