0

I followed this solution to cast base class to derived. However, it says that it is important not to add new instance vars. In my case, I have to add new fields in the derived class and cast to it:

class A:
    def __init__(self, foo):
        self.foo = foo

class B(A):
    def __init__(self, foo, bar):
        super(B, self).__init__(foo)
        self.bar = bar

a = A(10)

some_list = [a]
some_dict = {'a': a}

# cast all instances of a to B(foo=a.foo, bar=a.foo * 2)
some_list[0].__class__ = B
some_list[0].bar = some_list[0].foo * 2

assert some_list[0] == some_dict['a']

How dangerous it is? Will it work exactly as if it was created by using B.__init__ function or the object is not a real instance of class B? Are there any potential cases where this can lead to incorrect behavior?


My use case is to change behavior of some instances of A from the large library that contains definition of A. It hides the initialization of a = A(10) and its uses some_list = [a], some_dict = {'a': a} so I can't change them during construction. I resorted to extracting the instance from one place in the data structures created by this library and extending its behavior by subclassing. Since I have no idea about the internals of the library (they are not part of public API), I can't reliably track all references to the object that exist in the library data structure.

Curious
  • 507
  • 3
  • 16

0 Answers0