How to "cast" an object to a derived class?

Robert Latest boblatest at yahoo.com
Fri Sep 17 16:15:42 EDT 2021


Hi all, let's assume I'm using a module that defines some class "Opaque" and
also a function that creates objects of that type. In my program I subclass
that type because I want some extra functionality. But how can I "promote" a
given Opaque instance to the derived class? Of course I could just create an
instance of the derived type and copy all attributes from the original object
to the new one, but that either breaks when the opaque.py module changes, or it
requires introspection. It's easily done of course but seems overly clumsy. Is
there a more Pythonic way?

# this is the module opaque.py
class Opaque(): def __init__(self, x): assert isinstance(x, int) self.n = x

def make_opaque(): return Opaque(0)

# this is my program
import opaque class MyClass(opaque.Opaque):
    # generic __init__ b/c I don't want to have to know anything about that
    # class
    def __init__(self, *a, **k): super().__init__(*a, *k) self.__something = 0

    def get_something(self): return self.something

op = opaque.make_opaque()

# But I want to have this as type MyClass. This obviously doesn't work:
my_object = MyClass(op)
# But what does?


More information about the Python-list mailing list