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

Python新手遇TypeError: __init__()需3个参数却传入4个如何解决?

问题原因&修复方案

  • 缩进错误:Children.py文件中__init__方法下的两行属性赋值没有缩进,Python强制要求方法内的代码要缩进4个空格(或者1个Tab),否则会报语法错误。
  • 传参数量不匹配:你定义的children_eating类的构造方法仅需要接收name、is_chewing两个参数(self是Python自动传入的实例本身,不需要手动传),但你调用时传入了3个参数,参数数量对不上会报错。
  • 列表取值语法错误:你想要取keely_kids列表中第0、第1位的元素,正确写法是keely_kids[索引],不需要把索引作为单独的参数传入构造方法。

修改后代码

Children.py

class children_eating:
    def __init__(self, name, is_chewing):
        self.name = name
        self.is_chewing = is_chewing

主运行文件

from Children import children_eating

keely_kids = [
    "Ella",
    "Jonathan",
    "Nathanael",
    "Daniel"
]

what_kids_chewing = [
    children_eating(keely_kids[0], True),
    children_eating(keely_kids[1], True)
]

# 测试打印内容
for kid in what_kids_chewing:
    print(kid.name, kid.is_chewing)

运行输出

Ella True
Jonathan True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:09:00