Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init child with Parent instance

I have a function which return instances of the class Parent:

def generateParent():
   do_stuff
   return Parent(some_parameters)

Now I want to init a subclass of Parent with the results of a call to generateParent():

class Child(Parent):
    def __new__():
        return generateParent(some_other_parameters) 

The problem is, when I override some methods from Parent in Child and then call them in instances of Child in my program, the original Parent method gets called instead of the new one from Child. Am I doing something wrong here? Am I using the correct design here for my task?

EDIT: I don't have access neither to Parent nor generateParent()

Solution(thanks to @Paul McGuire's answer):

class Child(object):
    def __init__(self):
        self.obj = generateParent()

    def __getattr__(self, attr):
        return getattr(self.obj, attr)
like image 854
elyase Avatar asked Aug 11 '26 01:08

elyase


1 Answers

Since generateParent is not your code, then instead of inheritance, you might want to use containment and delegation. That is, instead of defining a subclass, define a wrapper class that contains the generated object, forwards method calls to it when needed, but can add new behavior or modified behavior in the wrapper.

In this question, the OP had a similar situation, having a class generated in a libary, but wanting to extend the class and/or modify some behavior of the class. Look at how I added a wrapper class in that question, and you might consider doing something similar here.

like image 83
PaulMcG Avatar answered Aug 13 '26 15:08

PaulMcG