Sharing method code between class instances

Larry Bates lbates at swamisoft.com
Fri Jan 24 11:19:53 EST 2003


I have a question about how to share code between classes.  I've searched
and just can't find anything that is clear enough for me to understand.

Consider: I have a simple class that will hold a field and formatting
(and eventually much more) information.

class field:
    def __init__(self, name, format):
        self.name=name
        self.format=format
        self.value=0
        return

    def draw(self):
        t=self.format % self.value
        return t

if __name__=="__main__":
    f1=field('field1','%i')
    f2=field('field2','%03i')
    .
    .
    .
    fn=field('fieldn','%i')

Problem: My program will create hundreds of instances of this field class
and
I'm worried about the code for each instance of the class being repeated
over
and over filling memory.  In this simple case it wouldn't be a problem, but
the
draw method will get rather large as I introduce MANY formatting parameters
like fill characters, float characters, picture formats, etc. the draw
method will
become quite large/complex.

Question:

If I define a base class like:

class fieldbase:
    def __init__(self, name, format):
        self.name=name
        self.format=format
        self.value=0
        return

    def draw(self):
        t=self.format % self.value
        return t

and then define

class field(fieldbase):
    def __init__(self, name, format)
        fieldbase.__init__(name, format)
        return

if __name__=="__main__":
    f1=field('field1','%i')
    f2=field('field2','%03i')
    .
    .
    .
    fn=field('fieldn','%i')


Have I eliminated the 100's of copies of the draw method that would be
maintained
by the first example?

I hope this makes sense to someone out there.  Thanks in advance for any
feedback.

-Larry Bates

email: lbates at swamisoft.com







More information about the Python-list mailing list