1

Let's say I have 2 classes A and B, where B inherits from A. B overrides some methods of A and B have a couple more attributes. Once I created an object b of type B, is it possible to convert it into the type A and only A ? This is to get the primitive behavior of the methods

1
  • 1
    There's nothing built-in generic way to do such a conversion. You could of course create a function or method that constructed an A from a B and returned it. Commented Nov 11, 2020 at 23:32

1 Answer 1

2

I don't know how safe it is, but you can reassign the __class__ attribute of the object.

class A:
    def f(self):
        print("A")

class B(A):
    def f(self):
        print("B")

b = B()
b.f() # prints B
b.__class__ = A
b.f() # prints A

This only changes the class of the object, it doesn't update any of the attributes. In Python, attributes are added dynamically to objects, and nothing intrinsically links them to specific classes, so there's no way to automatically update the attributes if you change the class.

Sign up to request clarification or add additional context in comments.

3 Comments

This assumes all the instance state actually makes sense for an object of type exactly A instead of B. It won't do any attribute fixing that might be necessary.
Interesting, does that mean instances do not store explicit references to their methods but instead use this class name to then retrieve methods? I though we would have to do something like a = A.__new__(A) then a.__dict__ = b.__dict__ but that's clearly not that strange of a solution. I new I should come here when I read the question title.
Methods and static attributes are accessed indirectly through the class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.