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 Answer
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.
3 Comments
user2357112
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.
cglacet
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.Barmar
Methods and static attributes are accessed indirectly through the class.
Afrom aBand returned it.