A colleague of mine demonstrated some code to me which I found quite interesting:
class A(object):
def evolve(self):
if self.foo > 10:
self.__class__ = B
class B(A):
def bar(self):
print "I'm a B"
... that's essentially the gist of it. The idea is to "specialize" an instance at runtime after other computations have been processed. I have been thinking about it, and even while it feels wrong (especially the assignment to __class__
), I can see nothing wrong with it, as long as the type hierarchy is properly taken into account.
Is there maybe a way to do this in Python without the assignment to __class__
?
Again, I don't see too much wrong with this, as the assignment to __class__
effectively only changes the resolution order... no?