[Tutor] How to use function from specific module and then switch to other module

Kent Johnson kent37 at tds.net
Fri Nov 7 04:36:42 CET 2008

On Thu, Nov 6, 2008 at 5:54 PM, Ertl, John C CIV 63134
<john.ertl at navy.mil> wrote:
> Classification: UNCLASSIFIED
> Caveat (s): FOUO
> I have a program that collects weather data from weather models.  I
> originally had a module that contained a bunch of function that I used.  So
> I just added it to the init of the class I was using and inherited the
> functions.  That worked great but now I have two different models that I can
> get weather from.   Each Module A and B have the exact same function names
> in them but they both do slightly different things.

It might help to see a working example of what you did for one model.
> The idea is as I step through a list I want to use a different function
> (same name but from a different module) for each element in the list.  How
> do I have a generic way to do this.
> for example for point 1 I want to use the rain function from Module A and
> then for point 2 I want to use the rain function from Module B.   At first
> though I would just init the class from either A or B for each point but I
> need the function from A or B to be able to use function from my main
> program...that is why the inheritance thing worked great for just one
> module.

Don't try to make the model A and B into base classes of the forecast.
Just pass the forecast object to the model. So your rain() method will
look more like this:
     def rain(self, fc):
           fc.calTime() # this function is in the main forecast class
           fc.rain = do stuff for model A

where fc will be the forecast instance.

You might also be able to use simple functions rather than classes:
     def rain(fc):
           fc.calTime() # this function is in the main forecast class
           fc.rain = do stuff for model A

then just call moduleA.rain(self) or moduleB.rain(self).

You might want to read about the Strategy pattern, that is what you
are doing. Here is a Python example of a class-based Strategy.

This example passes the strategy to the constructor but you can set it
in your pointInfo() method if you like. I would just make one function
to handle each point though:
for each in x.pointList:

def handlePoint(self, point):
   pointStrategy = ...
   pointStrategy.rain(self, point)



More information about the Tutor mailing list