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

Python Dataclasses疑问:实例化时触发TypeError的原因排查

解决TypeError: Person() takes no arguments错误

问题出在你没有给Person类添加@dataclass装饰器。虽然你导入了dataclass,但未将其应用到类上,这个类只是普通Python类,默认的__init__方法不接受任何参数,传参实例化时就会触发错误。

修正后的代码如下:

from dataclasses import dataclass

@dataclass
class Person():
    name: str
    age: int
    height: float
    email: str

person = Person('Joe', 25, 1.85, 'joe@dataquest.io')
print(person.name)

@dataclass装饰器会自动为类生成包含所有字段的__init__方法,让你可以通过位置参数或关键字参数实例化对象。除此之外,它还会自动生成__repr__、__eq__等常用方法,简化数据类的编写。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:14:50