2

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?
Community
  • 1
  • 1
Vroomfondel
  • 2,704
  • 1
  • 15
  • 29
  • 1
    Adapters and wrappers are nice patterns. You might want to consider them. :-) – Lennart Regebro Oct 08 '13 at 08:26
  • 1
    As Lennart mentioned Python has a good support for delegation so a simple adapter / wrapper might be the good solution. Another - less clean but sometimes a real life-saver - solution is monkeypatching. – bruno desthuilliers Oct 08 '13 at 09:00
  • 1
    Some additional points in http://stackoverflow.com/questions/3464061/cast-base-class-to-derived-class-python-or-more-pythonic-way-of-extending-class – PaulMcG Oct 08 '13 at 09:28
  • I think you can totally do this in your code if you are the only one doing this to the object. Here is my wish for subjectivity in an objective world: http://stackoverflow.com/questions/14946636/subject-oriented-or-refinements-with-builtin-python-objects – User Oct 08 '13 at 19:20

0 Answers0