Python中出现这样的问题TypeError: object() takes no parameters怎么解决?
1个回答
展开全部
class Person :
population=0
def __init__(self,name):
self.name=name
print ('Initializing %s' % self.name)
Person.population+=1
def sayHi(self):
print ('hi,My name is %s.' % self.name)
def howMany(self):
if Person.population==1:
print ('I am the current population .')
else:
print ('We have %d persons here ' % Person.population)
swaroop=Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam=Person('Abdul kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
如上面Python代码,是学习python类时遇到的一个小例子。但是在运行时会报错:
Traceback (most recent call last):
File "E:/PythonStudy/objvar.py", line 18, in <module>
swaroop=Person('Swaroop')
TypeError: object() takes no parameters
经过查阅资料才知道,是构造函数里的下划线的问题,
__init__(self,name)这个构造函数的左右下划线都是两个,我只用了一个,导致错误。
population=0
def __init__(self,name):
self.name=name
print ('Initializing %s' % self.name)
Person.population+=1
def sayHi(self):
print ('hi,My name is %s.' % self.name)
def howMany(self):
if Person.population==1:
print ('I am the current population .')
else:
print ('We have %d persons here ' % Person.population)
swaroop=Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam=Person('Abdul kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
如上面Python代码,是学习python类时遇到的一个小例子。但是在运行时会报错:
Traceback (most recent call last):
File "E:/PythonStudy/objvar.py", line 18, in <module>
swaroop=Person('Swaroop')
TypeError: object() takes no parameters
经过查阅资料才知道,是构造函数里的下划线的问题,
__init__(self,name)这个构造函数的左右下划线都是两个,我只用了一个,导致错误。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询