0

I have instance a of class A, and I want to make it also an instance of class B (which inherits from A).

I have tried this, but is is not behaving as expected:

class A:
    def __init__(self):
        self.a = 1

class B(A):
    def __init__(self):
        self.b = 2

a = A()
isinstance(a, A)   # True
B.__init__(a)
isinstance(a, B)   # False, I wished it was True...

I have seen this answer but I think my problem is a bit more general: here only the methods from B will apply to a, but I want a to be a full-fledged instance of B, i.e. also with member variables etc (as though a had been directly created as an instance of B, but with the inheritance from A in a state exactly similar to a).

How can I do this?? I don't mind creating a new instance if necessary, as I long as I can restore the exact same state in the end.

EDIT: I have also seen answers to this question, but they either only create a new instance of B and retrieve one field from a (that will be hard to extend to complicated A classes with many attributes) or just set a.__class__ = B which does not create attributes of B.

Ariane
  • 326
  • 2
  • 11
  • Does this answer your question? https://stackoverflow.com/questions/597199/converting-an-object-into-a-subclass-in-python – Alex Watt Nov 13 '20 at 13:10
  • Does this answer your question? [Converting an object into a subclass in Python?](https://stackoverflow.com/questions/597199/converting-an-object-into-a-subclass-in-python) – Alex Watt Nov 13 '20 at 13:10
  • 1
    in your code B is a subclass of A. `B(A)`. you want it the other way around `A(B)` – Lior Cohen Nov 13 '20 at 13:10
  • You basically need to combine both your approach and the other answer: set the `__class__` *and* run some sort of `__init__` on the object. Note that this really sounds like a bad idea in the first place, there are probably better approaches 99% of the time. – deceze Nov 13 '20 at 13:26
  • @LiorCohen can you explain your thought? Is there a reason for what you say? To me `A` is a generic class, and `B` is a subclass of `A` with additional functionalities. At some point I finally need these functionalities so I want to extend the class of `a` to `B`. Why should that be the other way round? – Ariane Nov 13 '20 at 13:26
  • @deceze could you explain why you think it is a bad approach, and how could it be circumvented? – Ariane Nov 13 '20 at 13:28
  • `B.__init__(a)` does not make a B type. it is just regular function. If you want "cast" make B __init__ accecpt another argument (`__init__(self, obj)` ) and assign obj attributes to self. – Lior Cohen Nov 13 '20 at 13:41

0 Answers0