How to convert (inherit) parent to child class?

I have a strong suspicion, nay, conviction, that there is something horribly wrong with your program design that it requires you to do this. In Python, unlike Java, very few problems require classes to solve. If there's a function you need, simply define it:

def function_i_need(a):
     """parameter a: an instance of A"""
     pass # do something with 'a'

However, if I cannot dissuade you from making your function a method of the class, you can change an instance's class by setting its __class__ attribute:

>>> class A(object):
...     def __init__(self):
...         pass
... 
>>> class B(A):
...     def functionIneed(self):
...         print 'functionIneed'
... 
>>> a = A()
>>> a.functionIneed()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'functionIneed'
>>> a.__class__ = B
>>> a.functionIneed()
functionIneed

This will work as long as B has no __init__ method, since, obviously, that __init__ will never be called.


Python does not support "casting". You will need to write B.__init__() so that it can take an A and initialize itself appropriately.