Skip to content Skip to sidebar Skip to footer

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, v

Solution 1:

In Python 2, make Foo inherit from object to make it a new-style class instead:

>>>classFoo(object):...def__init__(self, val1):...        self.val1 = val1...>>>classGoo(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:

defchangeToGoo(self)self.__class__ = Goo
    self.val2 = 'some value'

or re-use __init__:

defchangeToGoo(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.

Solution 2:

You could do :

defchangeToGoo(self, val2):
    return Goo(self.val1, val2)

Then call and assign, adding the extra attribute

a = a.changeToGoo(val2)

Post a Comment for "Python Change Self To Inherited Class"