class Rating():
def __init__(self, user, item, rating):
self.user = user
self.item = item
self.rating = rating
def __str__(self):
return str(user) + " " + str(item) + " " + str(rating)
def __repr__(self):
return str(user) + " " + str(item) + " " + str(rating)
data = open('data.dat').readlines()
records = ()
for i in data:
user, item, rating = i.split()
r = Rating(user, item, rating)
records += (r,)
print records
data = [A, B, C]
,我希望records
拥有(<Record> A, <Record> B, <Record> C)
。但它包含(<Record> C, <Record> C, <Record> C)
?
答案 0 :(得分:7)
您没有使用类属性,而是使用偶然定义的全局变量。
return str(user) + " " + str(item) + " " + str(rating)
应该是
return str(self.user) + " " + str(self.item) + " " + str(self.rating)
答案 1 :(得分:4)
您班级的__str__
是参考全球名称:
def __str__(self):
return str(user) + " " + str(item) + " " + str(rating)
这将是最后一次迭代:
user, item, rating = i.split()
需要将其修复为self.user
,self.item
等...
此外,我会更改你的线路更高效和Pythonic:
records = [Rating(*line.split()) for line in data]