Calling a method from invoking module

Dave Angel davea at ieee.org
Thu Oct 28 22:12:20 EDT 2010


On 2:59 PM, Baskaran Sankaran wrote:
> Hi,
>
> I have two classes in separate python modules and I need to access some
> methods of the either classes from the other. They are not in base and
> derived class relationship.
>
> Please see the example below. Foo imports Bar and inside the Foo class it
> creates a Bar obj and then calls Bar.barz(). Now before returning control,
> it has to call the track method in Foo.
>
> As I understand, I won't be able to use 'super' in this case, as there is no
> inheritance here. Also, I won't be able to move the track method to Bar as I
> need to track different bar types.
>
> Any suggestion on how to get this done would be great. Thanks in advance.
>
> Cheers
> - b
>
> ----------
>
> * foo.py *
>
> import bar
> class Foo:
>      def fooz():
>          print "Hello World"
>          b = Bar()
>          c = b.barz()
>          ...
>
>      def track(track_var):
>          count += 1
>          return sth2
>
>
> * bar.py *
> class Bar:
>      def barz():
>          track_this = ...
>          if Foo.track(track_this):
>              pass
>          else:
>              ...
>          return sth1
>
Your example is so vague it's hard to tell what the real requirements 
are.  Foo.track() won't work as coded, since it doesn't have a self 
argument.  If you really meant that, then make it a non-class function, 
and preferably define it in another module, included perhaps by both bar 
and foo.  Similarly, barz() cannot be called, since it wants zero 
arguments, and it'll always get at least one.

If I were you, I'd put both classes into the same module until you get 
their relationship properly understood.  And if they're really so 
intertwined, consider leaving them in the same module.  This isn't java.

In general, it's best not to have two modules importing each other.  
Generally, you can extract the common things into a separate module that 
each imports.  Failing that, you can have one import the other, and pass 
it whatever object references it'll need to run.  For example, at the 
end of foo.py, you'd have something like
   bar.Foo = Foo


If you really need to mutually import two modules, the first problem 
you're likely to bump into is if either of them is your script.  In 
other words, you need to have a separate file that's your script, that 
imports both foo and bar.

DaveA




More information about the Python-list mailing list