I have this kind of structure:
class Foo:
    def __init__(self, val1):
        self.val1 = val1
    def changeToGoo(self)
        HOW???
class Goo(Foo):
    def __init__(self, val1, val2):
        super(val1)
        self.val2 = val2
a = Foo(1)
a.changeToGoo()
'a' is now an instance of Foo
now i would like to change it to be an instance of Goo, by using the method "changeToGoo",  and add the other value.
How can this be done in Python?
I have tried:
self.__class__ = Goo
but when I check:
type(a)
it's still Foo, and not Goo.
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.
You could do :
def changeToGoo(self, val2):
    return Goo(self.val1, val2)
Then call and assign, adding the extra attribute
a = a.changeToGoo(val2)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With