Python类中为运动强度赋值并计算卡路里的问题求助
Hey there! Let's work through your problem together. You've got two key issues here: your setter methods aren't updating the instance properties correctly, and you need a clean way to map intensity levels to their calorie multiplier values. Let's tackle them one by one.
First: Fix the Setter Methods
Looking at your set_exercise, set_intensity, and set_duration methods, you're making a common mistake—you're assigning the new value to self.set_exercise (the method itself) instead of self.exercise (the instance property). That's why your updates aren't sticking! Here's how to fix each setter:
def set_exercise(self, exercise): self.exercise = exercise # Assign to the instance property, not the method def set_intensity(self, intensity): self.intensity = intensity def set_duration(self, duration): self.duration = duration
Also, your get_duration method has a small issue: it's trying to concatenate an integer (self.duration) with a string, which will throw an error. You need to convert the duration to a string first:
def get_duration(self): return f"{self.duration} minutes" # F-strings make this clean and readable
Second: Map Intensity to Calorie Values
For the intensity-to-number mapping, using a class-level dictionary is the perfect approach—it's clean, reusable, and easy to update. You can define this dictionary inside the ExerciseSession class (outside any methods) so all instances can access it. Then, add a method to calculate calories based on duration and intensity.
Here's the updated class with this logic:
class ExerciseSession: # Class-level dictionary to map intensity to calorie multipliers INTENSITY_MULTIPLIERS = { "Low": 3, "Medium": 6, "High": 12 } def __init__(self, exercise, intensity, duration): self.exercise = exercise self.intensity = intensity self.duration = duration def get_exercise(self): return self.exercise def get_intensity(self): return self.intensity def get_duration(self): return f"{self.duration} minutes" def set_exercise(self, exercise): self.exercise = exercise def set_intensity(self, intensity): # Optional: Add a check to ensure intensity is valid if intensity in self.INTENSITY_MULTIPLIERS: self.intensity = intensity else: raise ValueError(f"Invalid intensity. Choose from {list(self.INTENSITY_MULTIPLIERS.keys())}") def set_duration(self, duration): self.duration = duration def calculate_calories(self): # Get the multiplier, default to 0 if intensity is invalid (avoids crashes) multiplier = self.INTENSITY_MULTIPLIERS.get(self.intensity, 0) return self.duration * multiplier
How This Works:
INTENSITY_MULTIPLIERSis a class variable, so everyExerciseSessioninstance uses the same mapping—no need to redefine it for each object.- The
calculate_caloriesmethod usesdict.get()to safely retrieve the multiplier (returns 0 if the intensity isn't in the dictionary, which prevents unexpected errors). - The updated
set_intensityincludes a validation check to make sure only valid intensity values are set—this is optional but helps catch mistakes early.
Testing the Updated Code
If you run your test code now, plus call the new calculate_calories method, it should work as expected:
new_exercise = ExerciseSession("Running", "Low", 60) print(new_exercise.get_exercise()) # Output: Running print(new_exercise.get_intensity()) # Output: Low print(new_exercise.get_duration()) # Output: 60 minutes print(new_exercise.calculate_calories()) # Output: 180 (60 * 3) new_exercise.set_exercise("Swimming") new_exercise.set_intensity("High") new_exercise.set_duration(30) print(new_exercise.get_exercise()) # Output: Swimming print(new_exercise.get_intensity()) # Output: High print(new_exercise.get_duration()) # Output: 30 minutes print(new_exercise.calculate_calories()) # Output: 360 (30 * 12)
Key Takeaways
- Setter methods should update the instance's properties (like
self.exercise), not the method itself. - Class-level dictionaries are ideal for storing fixed mappings (like intensity to values) that all instances need access to—they're more maintainable than a bunch of
if/elifstatements. - Always validate inputs (like intensity) if you can—it prevents unexpected errors down the line.
内容的提问来源于stack exchange,提问作者TommyD543

