Why does the code in relation to both classes produce an error when executed?

Question:

I am trying to write a program that will: Create a class LanguageStudent with:

  • property languages – returns all languages, as a list, that the student knows.
  • method add_language(language) – adds a new language to the list of languages.

Create a class LanguageTeacher that inherits LanguageStudent and has one additional public method:

  • teach(student, language) – if LanguageTeacher knows the required language, it teaches LanguageStudent and
    returns true; otherwise it returns false.

For example, the following code shows how LanguageTeacher teaches LanguageStudent the new language (‘English’):

I am not sure entirely what I am doing wrong. I think I know how to correct it, but not entirely. Plus is this the best code to do what I’m supposed to do? I keep getting this error.

Traceback (most recent call last):
  File "C:Users....PycharmProjectstestmain.py", line 30, in <module>
    teacher = LanguageTeacher()
  File "C:Users.....PycharmProjectstestmain.py", line 17, in __init__
    super().__init__()
TypeError: LanguageStudent.__init__() missing 1 required positional argument: 'languages'
class LanguageStudent:
    def __init__(self, languages):
        self.languages = languages

def add_language(language):
    for language in languages:
        if language in languages:
            return
        else:
            languages.append(language)

class LanguageTeacher(LanguageStudent):
    def __init__(self):
        super().__init__()

def teach(student, language):
    if language not in student.languages:
        languages.append(language)
        return True
    else:
        return False

teacher = LanguageTeacher()
teacher.add_language('English')
student = LanguageStudent()
teacher.teach(student, 'English')
print(student.languages)
Asked By: Jack 248

||

Answers:

TypeError: LanguageStudent.init() missing 1 required positional argument: ‘languages’

This tells you that you are not passing enoughparameters to a function. The previous lines in the error message tell you that the problem is with these lines of code:

class LanguageTeacher(LanguageStudent):
    def __init__(self):
        super().__init__()

Here super().__init__() will call LanguageStudent.__init__():

class LanguageStudent:
    def __init__(self, languages):
        self.languages = languages

This method requires a languages parameter, but you are not providing it with an argument from LanguageTeacher.__init__(). One fix is to just add the parameter and then pass it to the super class:

class LanguageTeacher(LanguageStudent):
    def __init__(self, languages):
        super().__init__(languages)

p.s. There are other problems with your code, but I won’t address them here.

Answered By: Code-Apprentice
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.