You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为带有空列表初始化属性的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

  1. Incorrect Constructor Parameters: Your __init__ method required an extra new_tuple argument, but the problem states initialization should only take the semester term as input. This is why you got the TypeError when creating an instance without passing that argument.
  2. Class-Level Attributes: You defined grades and num_courses as class variables instead of instance variables. This would cause all GradeRecords instances to share the same course list and count, which is not intended.
  3. Wrong Initialization Logic: Your constructor tried to add a tuple to grades immediately, but the requirement says grades should start as an empty list, and num_courses should start at 0.
  4. Broken add_course Method: The method attempted to return grades (which wasn't properly scoped) and didn't update the num_courses count 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 empty grades list, and sets num_courses to 0—no extra arguments needed.
  • Adding Courses: The add_course method takes the three required parameters, creates the specified tuple, appends it to the instance's grades list, and updates num_courses to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:47:42