2

so please bear with me on this.

I struggle some in understanding certain aspects of the concept of inheritance.

As such, I was wondering, what would be the difference between implementing one class, say "Child", as the child of another, say "Parent", versus simply making "Child" create and utilize a "Parent" object within itself?

For example, given the parent class as:

class Parent:
    def __init__(self, arg):
        self.arg = arg

    def parent_method(self):
        print(self.arg)

What would be the difference between making and implementing a child class:

class Child(Parent):
    def __init__(self, arg):
        super().__init__(arg)

Child('foo').parent_method()

Versus:

class Child:
    def __init__(self, arg):
        self.parent = Parent(arg)

    def call_method(self):
        self.parent.parent_method()

Child('foo').call_method()

Both of which simply print:

foo

Is the only difference here syntactical? I mean, it definitely seems more efficient to use inheritance here, but is there something else I'm missing?

Thanks!

  • 2
    You are speaking about inheritance vs composition. That is a rather broad discussion, unfortunately I'm not sure it's a good fit for this site. – juanpa.arrivillaga Sep 17 '18 at 19:31
  • At it's core, inheritance is a tool for code reuse. Notice how you are already repeating yourself in the alternative to inheritance. – timgeb Sep 17 '18 at 19:31
  • Was going to say exactly that, one is inheritance and the other composition, one means a class is a subset of another one, the other means it is composed of them. Think about man and woman inheriting from human, VS human/man/woman being composed of hand and foot (a human can grab but he will use his hand). It is a matter of how the dependencies should work, and who holds responsibility for what. – E.Serra Sep 17 '18 at 19:32
  • For one thing, in your second example the parent's code operates on its own state which is separate from the child's. – Norrius Sep 17 '18 at 19:32
  • 1
    I suggest this old article https://glyph.twistedmatrix.com/tag/inheritance.html – nosklo Sep 17 '18 at 19:32
  • 1
    Using inheritance, `Parent` is part of the *interface* for `Child` as well as the implementation. Using composition, it's only part of the implementation. – chepner Sep 17 '18 at 19:37
  • Your question is very broad, For a start, in one example you have 1 object and the other you have 2. – Sayse Sep 17 '18 at 19:38
  • Type checkers like mypy, abstract base classes, `isinstance` works nicely, etc. I like to use a car metaphor for inheritance: Every `Prius` *is a* `Car`. A `Prius` doesn't have a `Car`. Also, inheritance let's you do neat stuff like `class OrderedCounter(Counter, OrderedDict): pass` – Patrick Haugh Sep 17 '18 at 19:44

0 Answers0