Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python change self to inherited class

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.

like image 292
Pasha Avatar asked Feb 14 '23 07:02

Pasha


2 Answers

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.

like image 53
Martijn Pieters Avatar answered Feb 17 '23 02:02

Martijn Pieters


You could do :

def changeToGoo(self, val2):
    return Goo(self.val1, val2)

Then call and assign, adding the extra attribute

a = a.changeToGoo(val2)
like image 22
jonrsharpe Avatar answered Feb 17 '23 03:02

jonrsharpe