The question is an extension of Reclassing an instance in Python where the OP very nicely explains the situation (class in foreign lib, subclass in own code). However, there remain some open details in the answers IMHO:
- if I reclass parent objects to child objects, is it valid at all to have a child constructor? After all, due to the absence of a copy-costructor (together with all problems of deep vs. shallow copying) I can't expect to correctly construct complete parent objects (even if I know the parent-constructor signature, see self._secret in the example). Would it be wise to lock the child constructor (by throwing an exception there e.g.)?
- how does C++ handle such a situation (inheritance)?
- do I break various OOP principles with the code? Is this a slap in the face of some design pattern? The basic idea, to retrofit some minor details of an object to my needs doesn't look so sinful after all.
foreign_lib.py:
lib_data = "baz"
class parent:
def __init__(self,foo,bar):
self._foo = foo
self._bar = bar
def do_things(self):
print(self._foo,self._bar)
def do_other_things(self,one2one_reference):
# this parent and the one2one_reference shall
# live in a 1:1 relationship
self._secret = one2one_reference # maybe ugly,but not in
# our hands to correct it
def some_lib_func():
p = parent("foo","bar")
p.do_other_things(lib_data)
return p
my_code.py:
class child(foreign_lib.parent):
def do_things: # but differently!
print(42)
super().do_things()
# do_other_things() shall be inherited as is
def __init__(self,p):
# out of luck here, no copy-constructor for parent?
@classmethod
def convert_to_child(cls,a_parent):
a_parent.__class__ = cls
a_child = child(some_lib_func()) # will not work correctly
a_child = child.convert_to_child(some_lib_func()) # maybe this one?