I thought all function and method arguments in Python were passed by reference, leading me to believe that the following code would work:
class Insect:
def status(self):
print "i am a %s" % self
class Caterpillar(Insect):
def grow_up(self):
self = Butterfly() # replace myself with a new object
return
class Butterfly(Insect):
pass
my_obj = Caterpillar()
my_obj.status() # i am a <__main__.Caterpillar instance at 0x100494710>
# ok, time to grow up:
my_obj.grow_up()
my_obj.status() # want new Butterfly object, but it is still Caterpillar! :(
How do I go about changing the object itself within a method call?
-- EDIT:
So far, the responses have been:
1) Change self.__class__ to change the class associated with the current object.
2) "Don't hold it that way."
The original question: How do I make a new object that takes the place of the old one from within a method call defined on the old class?
I think the answer might actually be "you can't."
-- EDIT2:
Why is everyone deathly afraid of saying "It's not possible"?