Python object conversion

python

Solution

This does the "class conversion" but it is subject to collateral damage. Creating another object and replacing its `__dict__` as BrainCore posted would be safer - but this code does what you asked, with no new object being created.

class A(object):
    pass

class B(A):
    def __add__(self, other):
        return self.value + other


a = A()
a.value = 5

a.__class__ = B

print a + 10

Problem

Assume that we have an object `k` of type `class A`. We defined a second `class B(A)`. What is the best practice to "convert" object `k` to `class B` and preserve all data in `k`?

Original source

Related problems