Python自定义Restaurant类运行无输出结果问题排查求助
问题定位与修复方案
你的代码没有输出的核心原因是缩进错误,其次还有潜在的无限递归问题,具体如下:
- 所有实例化类、打印属性、调用类方法的代码,全部错误缩进在了
open_restaurant方法内部。Python运行脚本时只会执行全局作用域的代码,方法内部的代码只有在方法被主动调用时才会执行,你当前全局作用域没有任何执行逻辑,自然不会有任何输出。 - 就算你触发了
open_restaurant方法的执行,也会直接出现无限递归崩溃:你在open_restaurant内部又调用了实例的open_restaurant()方法,会循环触发该方法执行,直到程序栈溢出报错。
修正后的可运行代码
class Restaurant: def __init__(self, mascalzone, it_fusion): self.mascalzone = mascalzone self.it_fusion = it_fusion def describe_restaurant(self): print(f"this restaurant is Italian and is named: {self.mascalzone}") def open_restaurant(self): print(f"the restaurant {self.it_fusion} is open , please come in!") # 实例化、属性打印、方法调用代码调整到全局作用域,和类定义同级 restaurant = Restaurant('open', 9) print(f"this:{restaurant.it_fusion}") print(f"that:{restaurant.mascalzone}") restaurant.describe_restaurant() restaurant.open_restaurant()
运行以上代码即可得到预期输出。
内容的提问来源于stack exchange,提问作者Uri
相关产品推荐
相关产品推荐

