Cast an object to a derived type in Python
Question: 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
    


Answer: 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)
    

