0

I'm still quite new to Python but I wanted to know if I could, instantiate a child object using an instantiated parent object. Something like this:

class Parent:
    def __init__(self, a):
        self.a = a
    def parent_function(self):
        print self.a
class Child(Parent):
    def __init__(self, parent, b):
        self.parent = parent
        self.b = b
    def child_function(self):
        print b
parent = Parent("a")
parent_2 = Parent("x")
child = Child(parent, "b")
child.parent_function()
child.child_function()
parent.a = "c"
child.parent_function()

Output:

a
b
c

To hopefully be a little clearer, I would like to inherit the functions and instance variables of an instantiated parent class object in a child class. I know I could make a static/instance variable in the child class that points to the specific parent object I would like to "inherit", but I wanted to know if there was a prettier way to do it

lemon
  • 14,875
  • 6
  • 18
  • 38
  • 1
    the child class already inherits the functions/variables of the parent so you would only need to instantiate the child class – Andrew Ryan Jun 03 '22 at 01:19
  • you would achieve this output by changing the last call from `child.parent_func()` to `child.parent.parent_func()` – dbakr Jun 03 '22 at 01:47
  • Welcome to Stack Overflow. It seems like you are generally confused about the terminology involved, as well as how inheritance generally works. I recommend looking up a specific tutorial on the topic. For example, you could try [the one built into the Python language documentation on the official Python web site](https://docs.python.org/3/tutorial/classes.html) (subsection 5 talks about inheritance, but you will want to read the whole thing). – Karl Knechtel Jun 03 '22 at 01:59

1 Answers1

1

by definition, child classes inherit all properties/methods of the parent class. therefore you don't need to reference any parent when you create/instantiate the child object.

class Parent:
    def __init__(self, a):
        self.a = a
    def parent_function(self):
        print(self.a)
class Child(Parent):
    def __init__(self, parent, b):
        super().__init__(b)
        self.parent = parent
    def child_function(self):
        print(self.b)

parent = Parent("a")
parent_2 = Parent("x")
child = Child(parent, "b")
child.parent_function()
child.child_function()
parent.a = "c"
child.parent.parent_function() # this will track parent
dbakr
  • 217
  • 1
  • 10