简体   繁体   中英

(Python Derived Classes) Not getting the correct output

This is my desired output:

Name: Smith, Age: 20, ID: 9999

Here is my code so far

class PersonData:
def __init__(self):
    self.last_name = ''
    self.age_years = 0

def set_name(self, user_name):
    self.last_name  = user_name

def set_age(self, num_years):
    self.age_years = num_years

# Other parts omitted

def print_all(self):
    output_str = 'Name: ' + self.last_name + ', Age: ' + str(self.age_years)
    return output_str


class StudentData(PersonData):
def __init__(self):
    PersonData.__init__(self)  # Call base class constructor
    self.id_num = 0

def set_id(self, student_id):
    self.id_num = student_id

def get_id(self):
    return self.id_num


course_student = StudentData()

course_student = StudentData()
course_student.get_id(9999)
course_student.set_age(20)
course_student.set_name("Smith")

print('%s, ID: %s' % (course_student.print_all(), course_student.get_id()))

At the moment, it isn't running. I would really appreciate it if someone could help out. It is returning a type error for line 34, and I am not sure how to correct it. Any help would be greatly appreciated.

You're invoking the parent init wrongly there...

Here's how you're supposed to do it:

class PersonData:
    def __init__(self):
        self.last_name = ''
        self.age_years = 0

    def set_name(self, user_name):
        self.last_name  = user_name

    def set_age(self, num_years):
        self.age_years = num_years

    # Other parts omitted

    def print_all(self):
        output_str = 'Name: ' + self.last_name + ', Age: ' + str(self.age_years)
        return output_str


class StudentData(PersonData):
    def __init__(self):
        super().__init__()  # Call base class constructor
        self.id_num = 0

    def set_id(self, student_id):
        self.id_num = student_id

    def get_id(self):
        return self.id_num


course_student = StudentData()

course_student = StudentData()
course_student.set_id(9999)
course_student.set_age(20)
course_student.set_name("Smith")

print('%s, ID: %s' % (course_student.print_all(), course_student.get_id()))

I also noticed that in the execution, you were calling course_student.get_id(9999) but I think you meant course_student.set_id(9999)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM