Bind an instance of a base to a subclass - can this be done?

Diez B. Roggisch deets at
Wed May 24 22:04:07 CEST 2006

Lou Pecora schrieb:
> I've been scanning Python in a Nutshell, but this seems to be either 
> undoable or so subtle that I don't know how to do it.
> I want to subclass a base class that is returned from a Standard Library 
> function (particularly, subclass file which is returned from open).  I 
> would add some extra functionality and keep the base functions, too.  
> But I am stuck.
> E.g. 
> class myfile(file):
>    def myreadline():
>       #code here to return something read from file
> Then do something like (I know this isn't right, I'm just trying to 
> convey the idea of what I would like)
> mf=myfile()
> mf=open("Afile","r")  
> s=mf.myreadline()     # Use my added function
> mf.close()            # Use the original file function
> Possible in some way?  Thanks in advance for any clues.

Nope, not in that way. But you might consider writing a proxy/wrapper 
for an object. That looks like this (rouch sketch from head):

class FileWrapper(object):
    def __init__(self, f):
       self._f = f

    def __getattr__(self, name):
       return getattr(self._f, name)

    def myreadline(self):

Then you do

f = FileWrapper(open(name, mode))


More information about the Python-list mailing list