0

I am trying to call the return values of a function within a class (Second) to another class(First) using super(). The class - Second is below class First. The code is as follows

class First(Second):
    def __init__(self):
        super().__init__()
        self.num1 = 1
    
    # add num
    def add_nums(self):
        print(self.num1 + self.set_num2()) 


class Second:
    def __init__(self):
        self.num2 = 2

    # Set num2
    def set_num2(self):
        return self.num2

a = First()
a.add_nums()

This actually works. However, if I add another class - Third below Second and call it in the class First, it doesn't work.

For instance, the following code doesn't work

class First(Second,Third):
    def __init__(self):
        super().__init__()
        self.num1 = 1
    
    # add num
    def add_nums(self):
        print(self.num1 + self.set_num2() + self.set_num3()) 


class Second:
    def __init__(self):
        self.num2 = 2

    # Set num
    def set_num2(self):
        return self.num2


class Third:
    def __init__(self):
        self.num3 = 3
    
    def set_num3(self):
        return self.num3

a = First()
a.add_nums()
jeff
  • 910
  • 2
  • 6
  • 25
  • 1
    The `__init__` method of `Second` should call `super().__init__()` – khelwood Apr 25 '22 at 16:50
  • Even in your first case, I can’t get it to run in a jupyter notebook. – Floh Apr 25 '22 at 16:51
  • 1
    By the way, having a method called `set_num2` that sets nothing and *returns* num2 is a horrible design. – khelwood Apr 25 '22 at 16:53
  • Even though `Second` doesn't extend any classes, it should still call `super().__init__()` to allow any of its own subclasses to work. To understand how this works, you can google "python method resolution order". – Code-Apprentice Apr 25 '22 at 16:55
  • Your first code does *not* work, because `Second` isn't defined yet when you try to define `First`. – chepner Apr 25 '22 at 17:00

0 Answers0