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

Ben Cartwright bencvt at
Thu May 25 01:03:02 CEST 2006

Lou Pecora wrote:
> 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.


  >>> mf=myfile()
  >>> mf=open("Afile","r")

Is actually creating an instance of myfile, then throwing it away,
replacing it with an instance of file.  There are no variable type
declarations in Python.

To accomplish what you want, simply instantiate the subclass:

  >>> mf=myfile("Afile","r")

You don't need to do anything tricky, like binding the instance of the
base class to a subclass.  Python does actually support that, e.g.:

  >>> class Base(object):
      def f(self):
          return 'base'
  >>> class Subclass(Base):
      def f(self):
          return 'subclass'
  >>> b = Base()
  >>> b.__class__
  <class '__main__.Base'>
  >>> b.f()
  >>> b.__class__ = Subclass
  >>> b.__class__
  <class '__main__.Subclass'>
  >>> b.f()

But the above won't work for the built-in file type:

  >>> f = file('foo')
  >>> f.__class__
  <type 'file'>
  >>> f.__class__ = Subclass
  TypeError: __class__ assignment: only for heap types

Again though, just instantiate the subclass.  Much cleaner.

Or if that's not an option due to the way your module will be used,
just define your custom file methods as global functions that take a
file instance as a parameter.  Python doesn't force you to use OOP for


More information about the Python-list mailing list