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

创建Animal类实例时触发TypeError错误,请问问题出在哪里?

问题

我定义了如下Animal类:

class Animal:
    def __int__(self, height, weight):
        self.height = height
        self.weight = weight

随后尝试通过以下代码创建Animal类的实例animal_1:

animal_1 = Animal(height=120, weight=80)

执行代码时触发错误:

TypeError: Animal() takes no arguments

请问我哪里出错了?

错误原因与修复方案

你把Python类的构造函数名字写错了——应该是__init__(前后各两个下划线+init),而不是__int__。

__int__是Python中用于将对象转换为整数类型的特殊方法,并非初始化类实例的构造函数。由于你没有定义正确的__init__方法,Python会使用默认的无参构造函数,此时传入height和weight参数自然会触发TypeError。

修复后的代码如下:

class Animal:
    def __init__(self, height, weight):
        self.height = height
        self.weight = weight

# 现在可以正常创建实例
animal_1 = Animal(height=120, weight=80)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 01:49:54