Calling a method from invoking module

Dave Angel davea at ieee.org
Fri Oct 29 20:12:27 CEST 2010


On 2:59 PM, Chris Rebert wrote:
> On Thu, Oct 28, 2010 at 8:33 PM, Baskaran Sankaran<baskarans at gmail.com>  wrote:
>> Sorry for the confusion; fooz(), track() and barz() are all members of their
>> respective classes. I must have missed the self argument while creating the
>> synthetic example.
>>
>> Yeah, I realize the mutual import is a bad idea. So, if I merge them into a
>> single module (but still retaining the two classes) will work right?
Yes, if you define them both in the same module, they can reference each 
other arbitrarily.  But you still have plenty of errors, some of which 
Chris has pointed out.  I can ignore most, but his point about calling a 
function without an instance is important, so I'll comment some more at end.
>>   I
>> guess, it will look like this after merging.
>>
>> Thanks again
>> -b
>>
>> * foo_bar.py *
>>
>> class Foo:
>>      def fooz(self):
>>          print "Hello World"
>>          b =ar()
>>          c =.barz()
>>          ...
>>
>>      def track(self, track_var):
>>          count +=
> That line will raise UnboundLocalError. Where's count initialized?
>
>>          return sth2
>>
>>
>> class Bar:
>>      def barz(self):
>>          track_this =..
>>          if Foo.track(track_this):
> You can't call an instance method on a class.
>
>
If you really need to call this on the class (because its data spans 
multiple instances, for example), then you should make it a 
classmethod.  Easiest way is as follows:

class Foo:
     def fooz(self):
         print "Hello World"
         b = Bar()
         c = b.barz()
         ...

     @classmethod
     def track(cls, track_var):
         count += 1

Note that the first argument is now the class, so by convention we call 
it cls, rather than self.  And that within a class method, you typically 
reference class attributes.  So you might want to use something like:

class Foo:
     count = 0          #I'm a class attribute
     def fooz(self):
         print "Hello World"
         b = Bar()
         c = b.barz()
         ...

     @classmethod
     def track(cls, track_var):
         cls.count += 1



DaveA




More information about the Python-list mailing list