Python :TypeError: this constructor takes no arguments报错原因

本文探讨了在使用Python进行面向对象编程时遇到的TypeError异常:thisconstructor takes no arguments。详细分析了错误原因,通常是因为__init__方法被误写为其他形式,如int。通过一个具体的Entity1类实例,展示了正确的__init__方法定义,帮助读者理解并避免此类常见错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初学Python,编写面向对象程序出现
TypeError: this constructor takes no arguments这样的异常,网上查了很多基本上都是说
__init__这个方法前后的下划线为2个,容易因为疏忽写成1个,就会报这个错,可是我的是通过编译工具PyCharm提示生成的怎么会出现这个问题呢,查了半天也没看出来,最后找了半天发现还是因为疏忽,导致init方法写成int方法,对于这类问题可以参考下这个

https://stackoverflow.com/questions/27017493/python-typeerror-this-constructor-takes-no-arguments

class Entity1:
   def __init__(self,name,age):
             self.name = name
             self.age = age

   def speak(self):
            print("name=%s,age=%d"% (self.name, self.age))

   def __repr__(self):
            return '<Person {}>'.format(self.name)

e1=Entity1("张三",22)
e2=Entity1("李四",25)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值