如何解决Python中__init__()缺失4个必填位置参数的TypeError?
问题分析与修复
错误原因
TypeError 问题:
- 你定义的
main类继承了car类,但car的__init__要求传入4个参数。调用main()时,Python会自动调用父类car的构造方法,但未传递必要参数,导致报错。 - 核心问题是
main不需要作为car的子类存在,它只是程序的执行入口,不该继承car。 - 另外,你把交互逻辑直接写在
main类的定义下,这属于类属性范畴,不是可执行的代码块,写法错误。
- 你定义的
之前的Unexpected Unindent Error:
- Python对缩进要求严格,
car类内的所有方法(__init__、paint_cost、top_speed)都需要缩进一级(通常4个空格),你提供的代码里这些方法的缩进不符合规范。
- Python对缩进要求严格,
修复后的代码
class Car: def __init__(self, body, engine, brand, model): self.body = body self.engine = engine self.brand = brand self.model = model def paint_cost(self): if self.body == 'truck': return 500 elif self.body == 'sedan': return 300 elif self.body == 'coupe': return 150 else: return 100 def top_speed(self): if self.body in ['sedan', 'coupe'] and self.engine == 'bigger': print('Faster') else: print('Slower') def main(): body = input('Enter the body type(truck,coupe,sedan): ') engine = input('Enter the engine type(bigger or smaller): ') brand = input('Enter the brand type: ') model = input('Enter the model: ') built_car = Car(body, engine, brand, model) option = input('Enter the option 1. to find paint cost or 2. to find top speed: ') if option == '1': print("Paint cost:", built_car.paint_cost()) else: built_car.top_speed() if __name__ == "__main__": main()
关键修改点
- 修正
car类内所有方法的缩进,确保符合Python规范(类内代码缩进4个空格)。 - 将
main类改为普通函数,去掉不必要的继承关系,避免构造方法参数错误。 - 使用
if __name__ == "__main__":作为程序入口,这是Python的标准写法,确保只有直接运行脚本时才执行main函数。 - 优化
paint_cost方法的条件判断,用elif替代多个if,逻辑更清晰。 - 变量名改为下划线命名法(如
built_car),符合Python的PEP8编码规范。
内容的提问来源于stack exchange,提问作者Alodian
相关产品推荐
相关产品推荐

