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

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()

关键修正点说明

  1. DateInfo类优化:将current_time改为返回时间字符串,让组合类可以存储并复用时间信息
  2. NutritionPlan构造函数调整:接收已初始化的Building实例(因为Building继承自Person,天然包含个人信息和营养计算能力),避免重复初始化参数
  3. 信息展示逻辑修正:调用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:30:50