I want to cast an object of type A to type B so I can use B's methods. Type B inherits A. For example I have class my class B:
class B(A):
def hello(self):
print('Hello, I am an object of type B')
My Library, Foo, has a function that returns an object of type A, which I want to cast to type B.
>>>import Foo
>>>a_thing = Foo.getAThing()
>>>type(a_thing)
A
>>># Somehow cast a_thing to type B
>>>a_thing.hello()
Hello, I am an object of type B
The usual way to do this is to write a class method for B that takes an A object and creates a new B object using the information from it.
class B(A):
@classmethod
def from_A(cls, A_obj):
value = A.value
other_value = A.other_value
return B(value, other_value)
a_thing = B.from_A(a_thing)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With