python学习日志_错误解析#5——Type Error: object() takes no parameters

本文记录了一次Python编程中遇到的TypeError,具体表现为'object() takes no parameters'。错误出现在尝试创建一个带有参数的实例时,但类的默认构造函数没有正确调用。问题根源在于将`__init__`方法误写为`__int__`。纠正这个拼写错误后,代码成功运行。此外,还提到Python中对象可以在创建后动态添加属性。

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

翻译:

类型错误: object()不接受参数

案例:(错误代码)

class Student(object):
	
	def __int__(self, name, score):
		self.name = name
		self.score = score

	def print_score(self):
		print self.score
		
Ronny = Student('Ronny', 97)
Ronny.print_score()
Ronny.age = 22
print Ronny.age

报错:

F:\pythonTest>python TestClass.py
Traceback (most recent call last):
  File "TestClass.py", line 10, in <module>
    Ronny = Student('Ronny', 97)

Type Error: object() takes no parameters

翻译:

F:\ pythonTest python TestClass.py 
回溯(最近一次通话):
TestClass文件”。第10行,<模块>。
罗尼=学生(罗尼,97)
类型错误:object()不接受参数

分析:

在构建对象时报错,类不需要参数,而我已经定义了默认构造函数是需要两个参数的,这是为什么的?原因大概率在定义的构造函数上,应该是没有调用到它。

检查一番,果然发现,默认构造函数是__init__,而我写成了__int__,我用的是UltraEdit,一样会提示颜色变换,

  


所以没有注意到,太粗心了!

更改后如下:

class Student(object):
	
	def __init__(self, name, score):
		self.name = name
		self.score = score

	def print_score(self):
		print self.score
		
Ronny = Student('Ronny', 97)
Ronny.print_score()
Ronny.age = 22
print Ronny.age

测试:


成功运行

同时,发现python中构造完成的对象可以随意增加属性变量,如图中Ronny这个学生对象,可以增加类定义中没有的age属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值