Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast an object to a derived type in Python

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
like image 963
travis1097 Avatar asked Dec 09 '25 02:12

travis1097


1 Answers

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)
like image 104
llb Avatar answered Dec 11 '25 16:12

llb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!