module inheritance? How to add a member to a class in a module

Ype Kingma ykingma at accessforall.nl
Thu May 10 21:11:44 CEST 2001


George Young wrote:
>
... 
> 
> Here's a sketch of the code; I'm trying to add the getnotify() member to
> pgdbCnx:
> 
> ----------------pgdb.py: the third party module I'd rather not modify
> per se-----------
> class pgdbCnx
>         def __init__(self, cnx):
>                 self.__cnx = cnx
>                 self.__cache = pgdbTypeCache(cnx)
>                 src = self.__cnx.source()
>                 src.execute("BEGIN")
>         def commit(self):
>                 src.execute("COMMIT")
> #a few other classes and some constants and module-level functions...
> 
> ---------------pgdb_enhanced.py---------
> from pgdb import *              #just get everything
> 
> class __tmp(pgdbCnx):             #now I have pgdbCnx from the import, I
> make new class from it
>     def __init__(self):
>         pgdbCnx.__init__(self)
>     def getnotify(self):        # add my member func to this tmp class
>         return self._pgdbCnx__cnx.getnotify()
> 
> class pgdbCnx(__tmp):             # shadow the imported class with this
> new enhanced class
>     def __init__(self):
>         tmp.__init__(self)
> 
> Unfortunately, this doesn't work.  In my application I get:
> Traceback (most recent call last):
>   File "./er.py", line 433, in notified
>     notify = db_conn.getnotify()
> AttributeError: pgdbCnx instance has no attribute 'getnotify'
> 

> What is the proper pythonic way to do such a thing?

You might add the method to all instances of pbdbCnx that need it.
I don't now how proper this is.
You can do it before the first method invocation:


def yourgetnotify(self): 
    return self.whateveryouneed

someCnx = pbdbCnx()
someCnx.getnotify = yourgetnotify # no braces

ntf = someCnx.getnotify()


Python is not statically typed.

Good luck,
Ype Kingma

email at xs4all.nl



More information about the Python-list mailing list