Python evangelists unite!

Jeff Shannon jeff at ccvcorp.com
Tue Dec 4 14:18:22 EST 2001


Jason Voegele wrote:

> I think an example is in order.  Say I have a class called "Book",
> that represents a book having a title, an author, a date of
> publication, etc.  In my application, I might instantiate a million
> Book objects.  But say that I only need to store one of them in the
> database.  Given the ability to add members to a specific object, I
> can add persistence support methods (such as object_id, mark_modified,
> etc.) to the single book instance that I need to store in the
> database.  (More precisely, the database binding could add these
> methods for me!)  If Ruby did not have this ability, the Book class
> would have to inherit from some sort of Persistent class.  This would
> mean that all one million books have these methods and variables to
> support persistence, even though only one book object actually needs
> them.

As a minor note, in general, methods don't create much "baggage" -- there is only
a single code object, as part of the class object, for each method, regardless of
how many instances of that class you create.  So you really aren't saving a
significant amount of much of anything by doing this.  I suppose that if every
instance needs a set of data members in order to support persistence, then you're
"wasting" that memory space for objects that won't be persisted, but in general,
this is not often a concern.

The *real* advantage for dynamically adding methods/attributes to an object, comes
when you don't have control over the original object.

If I have a commercial library to manage some task, and I want to store objects
from *that* library in my own object database, then I don't have the option of
having library objects inherit from some Persistent root class.  In Python this
can be solved in two ways, one of which is mix-in multiple inheritance, the other
of which is dynamically adding whatever methods and attributes are needed, as they
are needed.

In other words, it's not a solution for avoiding baggage, it's a solution for not
being *able* to put the needed "baggage" in place.   :)


Jyrinx  wrote:

> > (Of course, in Python
> > there's no such thing as a trivial subclass definition; you've got to
> > overload __init__ specifically and call __init__'s in each base class. This
> > ticks me off to no end.)

This is, of course, only true if the base *requires* initialization--many mix-in
classes don't--they simply provide methods and class-level data attributes,
without explicitly setting instance attributes in an __init__().


Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list