1
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)?

4

2 回答 2

7

您使用的不是类属性,而是您偶然定义的全局变量。

return str(user) + " " + str(item) + " " + str(rating)

应该看起来像

return str(self.user) + " " + str(self.item) + " " + str(self.rating)
于 2013-07-11T21:11:14.490 回答
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]
于 2013-07-11T21:11:29.997 回答