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

Python披萨订单系统开发遇AttributeError错误求助

披萨订单系统代码错误排查

问题描述

我是Python新手,正在开发披萨订单系统项目。需要创建名为Pizza的父类,以及Klasik和Margherita两个子类,在子类中定义配料和价格。当用户下单后需要获取对应信息,我的代码如下:

#create superclass
class Pizza(object):
    def _init_(self, description, cost):
        self.description=" "
        self.cost=0
    def get_description(self):
        return self.description
    def get_cost(self):
        return self.cost


#create subclasses

class Klasik(Pizza):
    def _init_(self, description, cost):
      self.description = "Ingredients: cheese, olive, corn"
      self.cost = 60.0

class Margherita(Pizza):
    def _init_(self):
        self.description="Ingredients: tomato, mozarella "
        self.cost = 50.0

pizza = input("Please select 1 or 2")
    if pizza=='1':
        pizza=Klasik()
    elif pizza=='2':
        pizza=Margherita()
    else :
        print("Please choose between: 1 or 2")

pizza_cost = pizza.self.cost()
print("your pizza costs" + pizza_cost)

选择1时出现错误:

AttributeError:'Klasik' object has no attribute 'self'

错误原因分析

  • 构造函数名称错误:Python构造函数是__init__(双下划线),你写成了_init_(单下划线),导致子类无法正确执行构造逻辑,实例化时参数不匹配也会触发问题。
  • 实例属性调用错误:pizza.self.cost()是完全错误的写法,self是类方法内部指代实例的关键字,外部调用实例属性应直接用pizza.cost,或调用你定义的get_cost()方法。
  • 缩进错误:if语句块缩进不符合Python规范,会直接导致语法报错。
  • 字符串拼接类型错误:print("your pizza costs" + pizza_cost)中pizza_cost是浮点数,无法直接与字符串拼接,需先转换为字符串类型。
  • 子类构造函数参数冗余:Klasik的构造函数定义了description, cost参数,但实例化时未传参,且子类不需要这些参数(你已直接赋值固定内容)。

修正后的代码

# 定义父类Pizza
class Pizza(object):
    def __init__(self, description, cost):
        self.description = description
        self.cost = cost
    
    def get_description(self):
        return self.description
    
    def get_cost(self):
        return self.cost


# 定义子类Klasik
class Klasik(Pizza):
    def __init__(self):
        # 调用父类构造函数初始化属性
        super().__init__("Ingredients: cheese, olive, corn", 60.0)

# 定义子类Margherita
class Margherita(Pizza):
    def __init__(self):
        super().__init__("Ingredients: tomato, mozarella", 50.0)


# 用户交互逻辑
pizza_choice = input("Please select 1 (Klasik) or 2 (Margherita): ")
pizza = None
if pizza_choice == '1':
    pizza = Klasik()
elif pizza_choice == '2':
    pizza = Margherita()
else:
    print("Please choose between: 1 or 2")

# 输出订单信息
if pizza:
    print(f"Your pizza: {pizza.get_description()}")
    print(f"Your pizza costs: {pizza.get_cost()} TL")

修正说明

  1. 修复构造函数:将所有_init_改为__init__,确保构造函数正常执行。
  2. 统一初始化逻辑:子类通过super().__init__()调用父类构造函数,避免重复代码。
  3. 修正属性调用:使用pizza.get_cost()或pizza.cost获取价格,删除错误的pizza.self.cost()写法。
  4. 修复缩进问题:调整if语句块缩进,符合Python语法规范。
  5. 处理类型拼接:使用f-string格式化输出,避免字符串与数值类型拼接错误。
  6. 完善交互逻辑:为pizza设置初始值None,避免用户输入错误时后续代码报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:48:30