Python changes the inherited class itself

I have this 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 as an instance of Goo using the "changeToGoo" method and adding another value.

How can this be done in Python?

I tried:

self.__class__ = Goo

but when I check:

type(a)

he is still foo, not goo.

+4
source share
2 answers

In Python 2, do Fooinherit from objectto create 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 the method changeToGoo():

def changeToGoo(self)
    self.__class__ = Goo
    self.val2 = 'some value'

or reuse __init__:

def changeToGoo(self)
    self.__class__ = Goo
    self.__init__(self.val1, 'some value')

, . Shapeshifting . .

+6

:

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

,

a = a.changeToGoo(val2)
+2

All Articles