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?
Advertisement
Answer
For all intents and purposes, a class B
object is a class A
object:
JavaScript
x
7
1
class A:
2
pass
3
class B(A):
4
pass
5
b = B()
6
print(isinstance(b, A)) # True
7
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.