Reputation: 262
I am writing a program that will at some point procedurally generate a new version of itself, save it to a file, and then import it from that file, overwriting relevant classes by the imported ones. And by saying that I mean the whole class will be redefined, not just specific methods changed.
So my question is, what happens to the already created instances of this class while it is redefined? Suppose you have:
class FooType():
def __init__(self):
pass
def doSomething(self):
print("Hello from old FooType")
foo = FooType()
# some code is executed here
class FooType():
def __init__(self, bar=None):
self.bar = bar if bar is not None else 'lorem ipsum'
def doSomething(self):
print("Hello world")
def somethingNew(self):
print("Hey, I can do this now!")
foo.doSomething()
which gives:
Hello from old FooType
meaning the foo object has not been updated, but why?
Upvotes: 2
Views: 801
Reputation: 867
Because you are simply re-binding the name FooType to another object (which is also a class). The old class object lives on in memory, as it can still be referenced via the instance foo
: id(foo.__class__)
. Python's "variables" are just names for objects that live somewhere in memory. When an object can't be referenced by any name, it gets garbage-collected.
It might be possible to re-assign the instance's type at runtime by modifying the __class__
attribute, but this is definitely not standard practice:
One option is using the adapter pattern, even though I'm not sure it's applicable to your use case: Change type of an object after its creation (typecasting in Python)
Upvotes: 3