0

I'm confused when I should import another class like:

# class_b.py
import ClassA

class ClassB:
    def __init__(self):
        self._classA = ClassA()

    def do_something(self):
        self._classA.doing_stuff()

and when I should inherit from the other class:

# class_b.py
import ClassA

class ClassB(ClassA):
    def __init__(self):
        super.__init__()

    def do_something(self):
        self.doing_stuff()

What are pros and cons of both approaches?

ppdyy
  • 31
  • 8

1 Answers1

0

For the sake of simplicity I would just stick with importing class since you would access the methods of the imported classes the same way (you still have to put Class.NameOfMethod either way) so aside from that I imagine it's a matter or coding style preference. I personally have never seen python written the way you showed in your second example. In my opinion it looks unecessarily verbose.

After doing a quick google on it seems to only be particularly useful when you're inheriting from a class that's within the same file.

class Person:

    def __init__(self, first, last):
        self.firstname = first
        self.lastname = last

    def __str__(self):
        return self.firstname + " " + self.lastname

class Employee(Person):

    def __init__(self, first, last, staffnum):
        super().__init__(first, last)
        self.staffnumber = staffnum


x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")

print(x)
print(y)

Reference https://www.python-course.eu/python3_inheritance.php

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
codehelp4
  • 132
  • 1
  • 2
  • 15
  • Why do you think that? I was honesty trying to answer the question. If I left something out free feel to advise or answer it yourself. I see answers like what I wrote all the time on here that are considered good and get selected to be the answer. – codehelp4 Jul 22 '18 at 00:17
  • After reading through your post and the reference you provide, I realize I was being unfair to you. Your intention is clearly good and the overall style of your answer is impeccable. It's just that I suspect that your experience with python is a bit limited and I happen to disagree with almost all of your assertions. – Mad Physicist Jul 22 '18 at 03:28