1

i've created a class workingstudent that inherits from class student but the inherited attributes(name, school) are seen as undefined by the program

class Student:
    def __init__(self, name, school):
        self.name = name
        self.school = school
        self.marks = []

    def average(self):
        total = sum(self.marks)
        ItemNo = len(self.marks)
        ave = (total / ItemNo)
        print(ave)

    def friend(self, friend_name):
        # return a new student called "friend_name" in the same school as self
        friend = Student(friend_name, self.school)
        return "Anna's friend is {} and he also goes to {}".format(friend.name, self.school)


Anna = Student("Anna", "st.peters")
Anna.marks = [1, 2, 3, 5, 8]
print(Anna.name)
print(Anna.school)
print(Anna.marks)
print(len(Anna.marks))
Anna.average()
print(Anna.friend("Alex"))


class workingstudent(Student):
    def __init__(self, workplace, salary):
        super().__init__(name, school)
        self.workplace = workplace
        self.salary = salary

    def get_salary(self):
        return self.salary

    def get_workplace(self):
        return self.workplace


workingAnna = workingstudent("google", "$10,000")
print(workingAnna.get_salary())
print(workingAnna.get_workplace())

when the code is run the inherited attributes of name and school in the workingstudent class are seen as undefined

1 Answer 1

1
class workingstudent(Student):
    def __init__(self, workplace, salary):
        super().__init__(name, school)

name and school are indeed not defined here. You should pass them to workingstudent.__init__:

def __init__(self, name, school, workplace, salary):

then

working_student = workingstudent('name', 'school', 'workplace', 999)

BTW, per PEP8 conventions the class name should be WorkingStudent.

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

2 Comments

so even if i'm inheriting i need to pass the attributes of the parent class in the init method of the child class? Thanks for the PEP8 reminder
@JordanRob yes, you are inheriting the class, not the instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.