In Python 2, make Foo
inherit from object
to make it a new-style class instead:
>>> class Foo(object):
... def __init__(self, val1):
... self.val1 = val1
...
>>> class Goo(Foo):
... def __init__(self, val1, val2):
... super(val1)
... self.val2 = val2
...
>>> f=Foo(1)
>>> f.__class__
<class '__main__.Foo'>
>>> f.__class__ = Goo
>>> f
<__main__.Goo object at 0x10e9e6cd0>
>>> type(f)
<class '__main__.Goo'>
Now you can change self.__class__
. In a changeToGoo()
method:
def changeToGoo(self)
self.__class__ = Goo
self.val2 = 'some value'
or re-use __init__
:
def changeToGoo(self)
self.__class__ = Goo
self.__init__(self.val1, 'some value')
This does make your objects somewhat monstrous, in that they change identity. Shapeshifting is rarely a great idea. You may want to rethink your use case.