Sharing Base Class members

Peter Hansen peter at engcorp.com
Mon Jul 12 10:51:10 EDT 2004


Greg Lindstrom wrote:

> I have a base class which does the heavy lifting associated with creating,
> modifying, and writing record segments for an application I've developed.
> One of the requirements of the app is I must track how many segments have
> been written to the output stream.  Since the Write() method is in the base
> class, I'd like to add a member in the base class, but I would like to
> "share" it across all objects created with the base class. Suppose
> 
> class myBase:
       segmentsWrittenCount = 0
>     def __init__(self, op=None):
>          self.op = op
>          self.segment = 'This is a test'
>     def Write(self):
>           if self.op is not None:  op.Write(self.segment)
             myBase.segmentsWrittenCount += 1
> 
> class A(myBase, op=None):
>      def __init__(self, op=op):
>          myBase.__init__(op=op)
> 
> class B(myBase, op=None):
>      def __init__(self, op=op):
>          myBase.__init__(op=op)

These two __init__ methods, as written, are redundant.  If you remove
them entirely, you'll get the same effect as what you have written
here (i.e. myBase.__init__ will be called with the op argument).

> Can, or rather *how*, can I add a member to myBase that will increment each
> time A.Write() or B.Write() is called?  I will then add a
> TotalSegmentsWritten() method to myBase to get the total number of segments
> written.

See code inserted above.  This is a "class variable" and as long
as you reference it with the class name instead of using "self."
you will get to that one single item defined in the base class.

-Peter



More information about the Python-list mailing list