如何为带有空列表初始化属性的Python类正确实现构造函数——GradeRecords类构造参数缺失错误排查
Fixing Your GradeRecords Class
Let's walk through the issues in your code and fix them to meet the specified requirements:
Key Problems in Your Original Code
- Incorrect Constructor Parameters: Your
__init__method required an extranew_tupleargument, but the problem states initialization should only take the semester term as input. This is why you got theTypeErrorwhen creating an instance without passing that argument. - Class-Level Attributes: You defined
gradesandnum_coursesas class variables instead of instance variables. This would cause allGradeRecordsinstances to share the same course list and count, which is not intended. - Wrong Initialization Logic: Your constructor tried to add a tuple to
gradesimmediately, but the requirement saysgradesshould start as an empty list, andnum_coursesshould start at 0. - Broken
add_courseMethod: The method attempted to returngrades(which wasn't properly scoped) and didn't update thenum_coursescount when adding a new course.
Corrected Code
class GradeRecords: def __init__(self, term): # Initialize instance-specific attributes as required self.term = term self.grades = [] # Starts empty self.num_courses = 0 # Initial course count is 0 def add_course(self, course_code, grade_100, num_credits): # Create the course tuple with the given parameters course_entry = (course_code, grade_100, num_credits) # Append the tuple to the grades list self.grades.append(course_entry) # Increment course count by 1 (since one course was added) self.num_courses += 1
How This Works
- Initialization: When you create an instance like
g1 = GradeRecords("Fall 2021"), the constructor sets the term, initializes an emptygradeslist, and setsnum_coursesto 0—no extra arguments needed. - Adding Courses: The
add_coursemethod takes the three required parameters, creates the specified tuple, appends it to the instance'sgradeslist, and updatesnum_coursesto reflect the new course.
Testing the Fixed Code
# Create a GradeRecords instance for Fall 2021 g1 = GradeRecords("Fall 2021") print(g1.term) # Output: Fall 2021 print(g1.grades) # Output: [] print(g1.num_courses) # Output: 0 # Add a course g1.add_course("CS101", 92, 3) print(g1.grades) # Output: [('CS101', 92, 3)] print(g1.num_courses) # Output: 1 # Add another course g1.add_course("MA102", 88, 4) print(g1.grades) # Output: [('CS101', 92, 3), ('MA102', 88, 4)] print(g1.num_courses) # Output: 2
This resolves the TypeError you encountered and fully meets all the requirements for the GradeRecords class.
内容的提问来源于stack exchange,提问作者gogo
相关产品推荐
相关产品推荐

