question about overriding method

Allan Streib streib at cs.indiana.edu
Wed Oct 29 18:36:51 EST 2003


Here is what I need to do:  The bsddb3 module
(http://pybsddb.sourceforge.net/) defines a class called _DBWithCursor
which has a method called set_location.  The code for set_location
looks like:

    def set_location(self, key):
        self._checkOpen()
        self._checkCursor()
        return self.dbc.set(key)

I want to in effect override that method so that in the last line it
calls set_range(key) instead of set(key).

But, I never deal with that class directly; an instance of it is
returned by the function "btopen" which is defined in the __init__.py
file of the bsddb3 module.  btopen is not a class method; it is just a
function defined in the bsddb3 namespace.

So when I write:

    import bsddb3
    mydb = bsddb3.btopen("mydbfile", "r")

how do I get mydb.set_location() to behave as I want?  I'm assuming
that there's a way to override this in my program; I don't really want
to change the bsddb3 __init__.py code.

My solution is:

    import bsddb3

    def my_set_location(self, key):
      self._checkOpen()
      self._checkCursor()
      return self.dbc.set_range(key)

    bsddb3._DBWithCursor.__dict__['set_location']=my_set_location


Which seems to do what I want.  Is there a better approach?

Allan




More information about the Python-list mailing list