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()
5
  • 1
    The __init__ method of Second should call super().__init__() Commented Apr 25, 2022 at 16:50
  • Even in your first case, I can’t get it to run in a jupyter notebook. Commented Apr 25, 2022 at 16:51
  • 1
    By the way, having a method called set_num2 that sets nothing and returns num2 is a horrible design. Commented Apr 25, 2022 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". Commented Apr 25, 2022 at 16:55
  • Your first code does not work, because Second isn't defined yet when you try to define First. Commented Apr 25, 2022 at 17:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.