Search code examples
pythonclassparent-childclass-structure

Creating a parent.child class structure where the child has a


I have the following code where a problem occurs because the child objects require parameters before they can create an instance. Do I need to create some kind of function to handle the creation of the child objects?

I want to be able to do:

a = parent()
a.other('param').double(2)
2
a.other('param').other_class('another_param').square(4)
16

This is my code:

class parent(object):

    def __init__(self):
        self.other = other_class2(self)
        self.answer = None

    def multiply(self,x,y):
        self.answer = x*y
        return x*y

    def add(self,x,y):
        self.answer = x+y
        return x+y


class other_class(object):

    def __init__(self,parent,inputed_param):
        self.parent = parent
        self.input = inputed_param

    def square(self,x):
        self.answer = self.parent.parent.multiply(x,x)
        return self.parent.parent.multiply(x,x)


class other_class2(object):

    def __init__(self,parent,inputed_param):
        self.parent = parent
        self.other_class = other_class(self)
        self.input = inputed_param

    def double(self,x):
        self.answer = self.parent.add(x,x)
        return self.parent.add(x,x)

In my actual code I am creating a python wrapper to automate tasks within a website that creates profiles, within each profile is a number of extracts. I thought this kind of tree structure would be the best way of managing all the associated routines.

I need a parent class to maintain the connection side of things to the website and I would like parent.profile(profile_id) to contain tasks/routines related to each profile. I would then like parent.profile(profile_id).extract(extract_id) to contain tasks/routines related to each extract.


Solution

  • You can build the class when you ask param. That code should realize your desired behavior.

    class parent(object):
    
        def __init__(self):
            self.other = lambda param: other_class2(self,param)
            self.answer = None
    
    class other_class2(object):
    
        def __init__(self,parent,inputed_param):
            self.parent = parent
            self.other_class = lambda param: other_class(self,param)
            self.input = inputed_param