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

《Python Crash Course》第9章习题9-2 第2行冒号语法错误求助

错误原因排查

  • 核心错误1:def关键字和构造方法名__init__之间缺少空格,你写的是def__init__,解释器无法识别这是方法定义,所以会抛出语法错误,报错指向冒号是解释器定位偏差导致的。
  • 错误2:类内部的所有方法没有缩进,Python要求类的成员方法必须缩进在类的代码块下,通常缩进4个空格。
  • 额外注意:你原代码里实例化Restaurant的代码也缩进在了类里面,要放到类的同级缩进位置。

修正后完整可运行代码

class Restaurant():
    def __init__(self, name, cuisine_type):
        self.name = name.title()
        self.cuisine_type = cuisine_type
        
    def describe_restaurant(self):
        msg = self.name + " serves wonderful " + self.cuisine_type + "."
        print("\n" + msg)
        
    def open_restaurant(self):
        msg = self.name + " is open. Come on in!"
        print("\n" + msg)
        
mean_queen = Restaurant('the mean queen', 'pizza')
mean_queen.describe_restaurant()

ludvigs = Restaurant("ludvig's bistro", 'seafood')
ludvigs.describe_restaurant()

mango_thai = Restaurant('mango thai', 'thai food')
mango_thai.describe_restaurant()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:36:04