Python组合模式实现求助:营养计划组合类构建遇阻
修正后的增肌营养需求计算程序
原代码中NutritionPlan类存在几个核心问题:
- 实例化
Person和Building时未传入必要的初始化参数,触发类型错误 date_time是局部变量,无法在类的其他方法中访问DateInfo.current_time仅打印时间而不返回值,无法存储供组合类使用- 直接打印对象会输出内存地址,而非实际信息
以下是修正后的完整代码:
import datetime import pytz calories = {'protein': 4, 'carbohydrates': 4, 'Fat': 9} building = { 'man': {'Calories': 44, 'Protein': 2.2, 'carbohydrates': 5, 'Fat': 0}, 'woman': {'Calories': 44, 'Protein': 2, 'carbohydrates': 5, 'Fat': 0} } class DateInfo: @staticmethod def current_time(): utc_time = datetime.datetime.utcnow() # 返回格式化后的时间字符串,而非直接打印 return pytz.utc.localize(utc_time).strftime("%m/%d/%Y-%H:%M:%S") class Person: def __init__(self, name, age, weight, sex, goal): self.name = name self.age = age self.weight = weight self.sex = sex self.goal = goal def personal_info(self): print(f'Name:{self.name}\nAge:{self.age}\nWeight:{self.weight}\nGoal:{self.goal}') class Building(Person): def __init__(self, name, age, weight, sex, goal): super().__init__(name, age, weight, sex, goal) def nutrition_details(self): factor = building['man'] if self.sex == 'Man' else building['woman'] total_calories = self.weight * factor['Calories'] gr_protein = self.weight * factor['Protein'] gr_carbohydrates = self.weight * factor['carbohydrates'] gr_fat = (total_calories - (gr_protein * calories['protein'] + gr_carbohydrates * calories['carbohydrates'])) // calories['Fat'] print(f'Total calories: {total_calories}\n gr of protein:{gr_protein}\n gr of carbohydrates:{gr_carbohydrates}\n gr of fat: {gr_fat}') class NutritionPlan: def __init__(self, person): # 直接调用静态方法获取时间并保存为实例属性 self.date_time = DateInfo.current_time() # 接收已初始化的Person/Building实例,实现组合 self.person = person def print_nutrition_details(self): print(f'Date: {self.date_time}') print('\nPerson Information:') self.person.personal_info() print('\nNutrition Plan:') self.person.nutrition_details() if __name__ == "__main__": person_1 = Building('Guillermo', 30, 82, 'Man', 'Building') # 使用组合类整合所有信息 nutrition_plan = NutritionPlan(person_1) nutrition_plan.print_nutrition_details()
关键修正点说明
- DateInfo类优化:将
current_time改为返回时间字符串,让组合类可以存储并复用时间信息 - NutritionPlan构造函数调整:接收已初始化的
Building实例(因为Building继承自Person,天然包含个人信息和营养计算能力),避免重复初始化参数 - 信息展示逻辑修正:调用
person实例的personal_info和nutrition_details方法来输出格式化内容,而非直接打印对象
运行修正后的代码,会输出整合了日期、个人信息和营养计划的完整结果:
Date: 02/02/2023-03:52:31 Person Information: Name:Guillermo Age:30 Weight:82 Goal:Building Nutrition Plan: Total calories: 3608 gr of protein:180.4 gr of carbohydrates:410 gr of fat: 138.0
内容的提问来源于stack exchange,提问作者Guillermo Barrios
相关产品推荐
相关产品推荐

