Mailing List Archive

How to "cast" an object to a derived class?
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?
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to "cast" an object to a derived class? [ In reply to ]
Stefan Ram wrote:
> Robert Latest <boblatest@yahoo.com> writes: But how can I "promote" a
>>given Opaque instance to the derived class?
>
> Sometimes, one can use containment instead of inheritance.

Nah, doesn't work in my case. I'm trying to write a wrapper around
xml.etree.ElemenTree and .Element to circumvent its idiotic namespace
handling. For that I need inheritance since I want to override the find..()
functions to return my derived MyElement classes. I think it could work but I
somehow need to convert the root Element to a MyElement.

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to "cast" an object to a derived class? [ In reply to ]
Robert Latest wrote at 2021-9-18 13:03 GMT:
>Stefan Ram wrote:
>> Robert Latest <boblatest@yahoo.com> writes: But how can I "promote" a
>>>given Opaque instance to the derived class?
>>
>> Sometimes, one can use containment instead of inheritance.
>
>Nah, doesn't work in my case. I'm trying to write a wrapper around
>xml.etree.ElemenTree and .Element to circumvent its idiotic namespace
>handling. For that I need inheritance since I want to override the find..()
>functions to return my derived MyElement classes. I think it could work but I
>somehow need to convert the root Element to a MyElement.

If the class is a pure Python class, then the `__class__` attribute
of its instances is writable. You could try to assign the
derived class -- at your own risk.



--
Dieter
--
https://mail.python.org/mailman/listinfo/python-list