Converting an instance to a subclass?

Jay O'Connor oconnor at bioreason.com
Fri Feb 16 15:43:26 EST 2001


Tom Bridgman wrote:
...
 
> However, I need to write a utility which will define methods that are
> only needed by the utility.  I really don't want these methods to be
> 'permanent' members of the class so I define them in a subclass as part
> of the utility.
> 
> Class B(A):
>    def Cleanup(self,x,y,z):
>        ...
> 
> Is there a way I can cast the instances of class A into instances of
> class B so I can use the additional methods?  I can't find anything
> about it in "Programming Python" but then I'm not quite sure where to
> look either.


One technique you can use is to add new instance methods to the objects
you wish to treat differently

------

#!/usr/bin/python

import new

class MyClass():

	def __init__(self):
		x = 100



# Seperate function, not part of MyClass
# but expects 'self' and references variables created in
MyClass.__init__()
def extraFunction(self):
	print "x = " + `self.x`

object = MyClass()

object.extra = new.instancemethod (extraFunction, object, MyClass)

object.extra()
------

This will print "x = 100"


This only adds the new method as an instance method to that one object. 
It does not affect other instances of MyClass, or MyClass itself

So just declare your extra methods seperate from the class and add them
as needed to the appropriate objects

Take care,
Jay O'Connor
joconnor at cybermesa.com



More information about the Python-list mailing list