Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate an object into an instance of one its subclasses

Tags:

python

oop

Is it possible to mutate an object into an instance of a derived class of the initial's object class? Something like:

class Base():
    def __init__(self):
        self.a = 1

    def mutate(self):
        self = Derived()

class Derived(Base):
    def __init__(self):
        self.b = 2

But that doesn't work.

>>> obj = Base()
>>> obj.mutate()
>>> obj.a
1
>>> obj.b
AttributeError...

If this isn't possible, how should I do otherwise?
My problem is the following: My Base class is like a "summary", and the Derived class is the "whole thing". Of course getting the "whole thing" is a bit expensive so working on summaries as long as it is possible is the point of having these two classes. But you should be able to get it if you want, and then there's no point in having the summary anymore, so every reference to the summary should now be (or contain, at least) the whole thing. I guess I would have to create a class that can hold both, right?

class Thing():
    def __init__(self):
        self.summary = Summary()
        self.whole = None

    def get_whole_thing(self):
        self.whole = Whole()
like image 328
Gohu Avatar asked Oct 19 '25 11:10

Gohu


1 Answers

Responding to the original question as posed, changing the mutate method to:

def mutate(self):
    self.__class__ = Derived

will do exactly what was requested -- change self's class to be Derived instead of Base. This does not automatically execute Derived.__init__, but if that's desired it can be explicitly called (e.g. as self.__init__() as the second statement in the method).

Whether this is a good approach for the OP's actual problem is a completely different question than the original question, which was

Is it possible to mutate an object into an instance of a derived class of the initial's object class?

The answer to this is "yes, it's possible" (and it's done the way I just showed). "Is it the best approach for my specific application problem" is a different question than "is it possible";-)

like image 166
Alex Martelli Avatar answered Oct 21 '25 01:10

Alex Martelli