0
class School:
    def __init__(self, school_name):
        self._school = school_name

class Exam:
    def __init__(self, exam_name):
        self._exam_name = exam_name
    def credit(self):
        return 3

class Test(School, Exam):
    def __init__(self, school_name, exam_name):
        self._date = "Oct 7"
        super().__init__(school_name, exam_name)

test = Test('Success', 'Math')
print(test._school) 
print(test._exam_name) 

I just want to know why super().init() can't work here. And if I insist to use super(), what's the correct way to do so that I can pass in the school_name and exam_name successfully.

3
  • 2
    The biggest issue is the semantics are wrong and that is causing the code to be confusing. A Test is not a kind of School. This is a case where composition makes more sense. Commented Oct 8, 2021 at 15:02
  • super().__init__(school_name, exam_name) doesn't work because neither of the inherited implementations take two (three, with self) parameters. Also neither of them calls super themselves, so only one will get invoked anyway. Commented Oct 8, 2021 at 15:04
  • If you have an instance method (generally true for __init__) you need to get the class, and an easy way to do that is just type(self), then you can access the __mro__ attribute which is a tuple of classes that your class inherits from. calling __init__ on Exam from Test.__init__ could then look like: type(self).__mro__[1].__init__(*args, **kwargs) Commented Oct 8, 2021 at 15:21

1 Answer 1

2

Super function only calls the parent class from MRO order. Acc to this, your prefered class would be School and the init of School will be called. You have to give only school_name as parameter while calling super().__init__(self,school_name). But if you want to call particular __init__(), then it is better to use <parent_class>.<method>(<parameters>). If you want to call both the init functions, try doing this:

class School:
    def __init__(self, school_name):
        self._school = school_name

class Exam:
    def __init__(self, exam_name):
        self._exam_name = exam_name
    def credit(self):
        return 3

class Test(School, Exam):
    def __init__(self, school_name, exam_name):
        self._date = "Oct 7"
        School.__init__(self,school_name)
        Exam.__init__(self,exam_name)

test = Test('Success', 'Math')
print(test._school) 
print(test._exam_name)

Try doing this

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.