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

Python实现披萨信息录入与计价功能时函数属性查找失败问题

问题根源
  • get_pizza_info 内部的size、meats、veg、quantity均为局部变量,你没有将其绑定为函数的属性,函数执行结束后这些值直接被回收,calc_pizza_charge自然无法访问到对应的函数属性。
  • calc_pizza_charge首行错误将get_pizza_info.size赋值为range(1,4),该range对象永远无法匹配后续的1/2/3整数判断条件,尺寸定价逻辑完全失效。
  • 总价计算逻辑放在了成本参数赋值之前,计算时用的都是未更新的初始参数,结果不符合预期。
  • get_pizza_info定义的四个形参属于冗余内容,内部已经用input的输入值完全覆盖了参数传入的内容,没有实际作用。
修正代码

这里提供符合你原有函数属性思路的修正版本:

def calc_pizza_charge():
    # 先根据录入的信息计算各项成本
    if get_pizza_info.size == 1:
        size_cost = 6.50
    elif get_pizza_info.size == 2:
        size_cost = 9.50
    else:
        size_cost = 11.50
    meats_cost = (get_pizza_info.meats - 1) * 3.50
    veg_cost = (get_pizza_info.veg - 1) * 1.50
    # 再计算总价
    total = (size_cost + meats_cost + veg_cost) * get_pizza_info.quantity
    print("Your total is $", "{:,.2f}".format(total))


def get_pizza_info():
    # 录入信息并做范围修正
    size = int(input("Enter size from 1-3: "))
    meats = int(input("Enter number of meat toppings "))
    veg = int(input("Enter number of non-meat toppings "))
    quantity = int(input("Enter number of these pizzas "))
    size = 3 if size >= 4 else 1 if size <=1 else size
    meats = 1 if meats <=1 else meats
    veg = 1 if veg <=1 else veg
    # 将修正后的值绑定为函数属性
    get_pizza_info.size = size
    get_pizza_info.meats = meats
    get_pizza_info.veg = veg
    get_pizza_info.quantity = quantity

# 调用示例
if __name__ == '__main__':
    get_pizza_info()
    calc_pizza_charge()

也可以采用更符合Python开发规范的返回值传参方案,避免依赖函数属性这种非常规的传值方式:

def calc_pizza_charge(size, meats, veg, quantity):
    if size == 1:
        size_cost = 6.50
    elif size == 2:
        size_cost = 9.50
    else:
        size_cost = 11.50
    meats_cost = (meats - 1) * 3.50
    veg_cost = (veg - 1) * 1.50
    total = (size_cost + meats_cost + veg_cost) * quantity
    print("Your total is $", "{:,.2f}".format(total))


def get_pizza_info():
    size = int(input("Enter size from 1-3: "))
    meats = int(input("Enter number of meat toppings "))
    veg = int(input("Enter number of non-meat toppings "))
    quantity = int(input("Enter number of these pizzas "))
    size = 3 if size >= 4 else 1 if size <=1 else size
    meats = 1 if meats <=1 else meats
    veg = 1 if veg <=1 else veg
    return size, meats, veg, quantity

# 调用示例
if __name__ == '__main__':
    pizza_info = get_pizza_info()
    calc_pizza_charge(*pizza_info)

内容的提问来源于stack exchange,提问作者Grelm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:18:02