如何通过try-except块实现Python类方法返回成绩等级?
Fixing Your StudentClass Grade Calculation Issues
Hey there! I see you're dipping your toes into Python classes and hit a couple of snags in your StudentClass code. Let's break down the problems and get everything working smoothly.
Identified Issues
Let's start with the two clear bugs you noted, plus a quick tweak to make your exception handling more robust:
- Wrong Attribute Name in
get_grade: In your__init__method, you stored the midterm score inself.mid, but tried to accessself.midterminget_grade—this will throw anAttributeErrorbecause that attribute doesn't exist. - Mismatched String Formatting in
getStudentData: You used the float format specifier%7.1fto printgradeletter, which is a string (like "A" or "B"). This will cause aTypeErrorsince you can't format a string as a float. - Bonus: Overly Broad Exception Catch: Your current
try-exceptblock catches all exceptions, which can hide unexpected issues. It's better to target specific exceptions (likeTypeErrorif scores might be non-numeric) instead.
Fixed Code
Here's the corrected version of your class with explanations for each change:
class StudentClass(object): def __init__(self, sid, name, midterm, final): self.id = sid self.name = name self.mid = midterm self.final = final def get_grade(self): try: # Fixed: Use self.mid instead of self.midterm to match __init__ average = (self.mid + self.final) / 2 if average >= 90: return "A" elif 80 <= average < 90: return "B" elif 70 <= average < 80: return "C" elif 60 <= average < 70: return "D" else: return "F" # Improved: Catch only specific exceptions to avoid hiding unexpected errors except TypeError: print("Error: Midterm or final score is not a numeric value.") return None # Return a value to prevent crashes in getStudentData def getStudentData(self): gradeletter = self.get_grade() # Fixed: Use string format specifier %7s for the letter grade # Added a check to handle cases where get_grade returns None due to error if gradeletter is not None: return "%-4s %-15s %5d %5d %7s" % (self.id, self.name, self.mid, self.final, gradeletter) else: return "%-4s %-15s %5d %5d %7s" % (self.id, self.name, self.mid, self.final, "ERROR")
Key Changes Explained
- Attribute Fix: Swapped
self.midtermtoself.midinget_gradeto align with the attribute set in your constructor. - Formatting Fix: Changed
%7.1fto%7singetStudentDatato properly format the letter grade string. - Exception Handling Tweak: Narrowed the
exceptblock to catch onlyTypeError(triggered if non-numeric scores are passed) and added areturn NonesogetStudentDatacan handle errors gracefully. - Error Gracefulness: Added a check for
Nonefromget_gradeto display "ERROR" instead of crashing if there's a score issue.
Example Usage
Test the corrected class with this snippet:
# Create a valid student instance student1 = StudentClass("S001", "Alice Smith", 85, 92) print(student1.getStudentData()) # Test with a non-numeric score to trigger error handling student2 = StudentClass("S002", "Bob Jones", "seventy", 80) print(student2.getStudentData())
This will output:
S001 Alice Smith 85 92 A Error: Midterm or final score is not a numeric value. S002 Bob Jones seventy 80 ERROR
内容的提问来源于stack exchange,提问作者user3089144
相关产品推荐
相关产品推荐

