Sharing method code between class instances

Daniel Dittmar daniel.dittmar at sap.com
Fri Jan 24 17:35:23 CET 2003


Larry Bates wrote:
> 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.

No need to worry. The code for the draw method is attached to the class, not
each individual instance.

>>> field.draw
<unbound method field.draw>
>>> field.draw.im_func
<function draw at 0x00769A60>
>>> f1 = field ()
>>> f2 = field ()
>>> f1.draw.im_func
<function draw at 0x00769A60>
>>> f2.draw.im_func
<function draw at 0x00769A60>

As you can see, the actual method code is the same, regardless of the
instance.

Daniel







More information about the Python-list mailing list