I am working with two classes in Python, one of which should be allowed to have any number objects from another class as children while keeping an inventory of these children as an attribute. Inheritance seemed like the obvious choice for this parent<>child situation but instead what I have arrived at is an example of composition. Here is the simplified code:
class Parent:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
self.kids = []
def havechild(self, firstname):
print(self.firstname, "is having a child")
self.kids.append(Child(self, firstname))
class Child(Parent):
def __init__(self, parent, firstname):
self.parent = parent
self.firstname = firstname
self.lastname = parent.lastname
So basically, while it seems to make intuitive sense to have Child() inherit from Parent(), removing the inheritance, does not change anything at all. The only benefit I can see for leaving Child(Parent) instead of just class Child() would be if I needed to add a lot more methods to Parent that I would like Child to inherit. Using the self.parent = parent, I already have access to any additional future attributes of the Parent.
Is there another way to use pure inheritance rather than passing the Parent instance into the Child constructor (composition)?