PyCharm中执行carstuff命令时误调用Python内置help菜单而非自定义帮助菜单
问题根源
- 类内方法调用错误:你在
askCommand方法中直接执行help(),默认调用的是Python全局内置的帮助工具,而非你在Commands类中定义的自定义help实例方法,调用类内实例方法需要加self.前缀。 - 类方法调用逻辑错误:你在main.py中直接用
Commands.askCommand(Commands)调用类方法的写法不符合面向对象规范,需要先实例化Commands类得到实例对象,再通过实例调用方法。
修复步骤
1. 修改commands.py文件
调整方法调用逻辑,删除类定义下多余的pass:
class Commands: def askCommand(self): command = input("Enter command: ") if command == "carstuff": # 改为调用自身的自定义help方法 self.help() elif command == "sell": pass elif command == "addcar": pass def help(self): print( "carstuff: Brings up the help menu\nsell: Sells the current car\naddcar: Adds another car" )
2. 修改main.py文件的调用逻辑
先实例化Commands类再调用实例方法:
from car import Car from commands import Commands print("Welcome to Craigslist on the command line! Start by entering your car info below.") brand = input("Enter your car brand: ") model = input("Enter your car model: ") year = input("Enter your car's year: ") condition = input("Enter your car's condition: ") car = Car(brand, model, year, condition) print("Your car's price is: " + str(car.price)) print("Now that you've listed your car, you can use commands now!\n") # 先实例化再调用方法 cmd_instance = Commands() cmd_instance.askCommand()
可选:修复car.py中的潜在问题
你当前的car.py存在几处逻辑错误,后续开发到对应功能时可以同步修改:
class Car: def __init__(self, brand, model, year, condition): self.brand = brand self.model = model self.year = year self.condition = condition self.price = len(model) * 0.75 * 3000 if self.condition == "Bad": # 原写法只做了运算没赋值给price self.price -= 100 elif self.condition == "Brand New": self.price += 100 def Sell(self): sure = input("Are you sure you want to sell? (Y/N): ") # 原or判断逻辑错误,要分别判断变量的值 if sure == "Y" or sure == "y": self.sellprice = self.price % 75 # 数字不能直接和字符串拼接,要转成str print("You got " + str(self.sellprice) + " from this car.") elif sure == "N" or sure == "n": print("Sell cancelled.\n")
内容的提问来源于stack exchange,提问作者kooljcid
相关产品推荐
相关产品推荐

