当学习面向对象的类和实例的时候,我一开始输入书中的代码,结果出现了object() takes no parameters问题,过程如下:
class Student(object):
def _init_(self,name,score):
self.name = name
self.score = score
def print_score(self):
print '%s: ,%s' % (self.name,self.score)
>>> bart = Student('Bart Simpon',49)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
bart = Student('Bart Simpon',49)
TypeError: object() takes no parameters
原因通过搜索,已解决。问题是init前面和后面都应该有两天下划线,咋一看书上的程序,原以为是前后各有一条下划线,在原程序上在init两边再各添一条下划线即可:
class Student(object):
def __init__(self,name,score):
self.name = name
self.score = score
def print_score(self):
print '%s: ,%s' % (self.name,self.score)
>>> bart = Student('Bart Simpon',49)
>>> bart.name
'Bart Simpon'
>>> bart.score
49
问题解决,其实上下对比一下,双下划线跟单下划线还是有一定区别的,但是如果不注意还是很容易看错。
特殊变量用双下划线开头、双下划线结尾的变量,类似__xxx__.