(Python派生类)未获得正确的输出

时间:2019-11-05 00:39:23

标签: python class object inheritance

这是我想要的输出:

Name: Smith, Age: 20, ID: 9999

到目前为止,这是我的代码

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()))

目前,它没有运行。如果有人可以帮忙,我将不胜感激。它返回第34行的类型错误,我不确定如何更正它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您在此处错误地调用了父init ...

这是您应该执行的操作:

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()))

我还注意到在执行过程中,您正在呼叫course_student.get_id(9999),但我认为您的意思是course_student.set_id(9999)