Bind an instance of a base to a subclass - can this be done?
bencvt at gmail.com
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.
> 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)
> s=mf.myreadline() # Use my added function
> mf.close() # Use the original file function
> Possible in some way? Thanks in advance for any clues.
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:
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):
>>> class Subclass(Base):
>>> b = Base()
>>> b.__class__ = Subclass
But the above won't work for the built-in file type:
>>> f = file('foo')
>>> 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