Python中小錯誤 之 object() takes no parameters

勿在浮沙築高臺LS發表於2017-01-25
 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
swaroop=Person(‘Swaroop’)
TypeError: object() takes no parameters

經過查閱資料才知道,是建構函式裡的下劃線的問題,

init(self,name)這個建構函式的左右下劃線都是兩個,我只用了一個,導致錯誤。

相關文章