Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cast Python class to parent class

I have class A. I need to store an additional value on class A so I extend it, creating class B which includes a my_variable attribute. I have a load of code that uses class B, but at the end of that code, I need to return a class A object.
How can I do this?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For all intents and purposes, a class B object is a class A object:

class A:
    pass
class B(A):
    pass
b = B()
print(isinstance(b, A)) # True

It will even pass type annotations this way. There is no need to cast the object, because it already is an instance of the parent class.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading