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

如何解决Python中__init__()缺失4个必填位置参数的TypeError?

问题分析与修复

错误原因

  1. TypeError 问题:

    • 你定义的main类继承了car类,但car的__init__要求传入4个参数。调用main()时,Python会自动调用父类car的构造方法,但未传递必要参数,导致报错。
    • 核心问题是main不需要作为car的子类存在,它只是程序的执行入口,不该继承car。
    • 另外,你把交互逻辑直接写在main类的定义下,这属于类属性范畴,不是可执行的代码块,写法错误。
  2. 之前的Unexpected Unindent Error:

    • Python对缩进要求严格,car类内的所有方法(__init__、paint_cost、top_speed)都需要缩进一级(通常4个空格),你提供的代码里这些方法的缩进不符合规范。

修复后的代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:55:24