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
相关产品推荐
相关产品推荐

