0

该问题的答案将起作用,或者我已经读到您不需要实际命名它们......所以我尝试了这个:

class Entry():
    __slots__ = ('name', 'gender', 'occurances')

def mkEntry(name_foo, gender_foo, occurances_foo):
    myEntry = Entry
    myEntry.name = name_foo
    myEntry.gender = gender_foo
    myEntry.occurances = occurances_foo
    return myEntry

def topTwenty(fileName):
    file = open(fileName)
    topTwenty = []
    femaleCount = 0
    maleCount = 0
    for line in file:
        a = line.split(",")
        if a[1] == 'F' and femaleCount < 20:
            topTwenty.append(mkEntry(a[0], a[1], a[2]))
            femaleCount = femaleCount + 1
    print(topTwenty[7].name)

但是 print(topTwenty[7].name) 正在打印我对 topTwenty[20].name 的期望

有什么帮助吗?

4

1 回答 1

1

你需要做myEntry = Entry()的就是创建一个类的实例。现在你只是每次都覆盖同一个类的属性,并且每次都将同一个类附加到列表中。您的列表仅包含 20 次相同的项目。

无论如何,这是一种奇怪的做事方式。为什么不将该代码从类中mkEntry移到一个类中,以将初始化与类保持在一起__init__Entry

于 2013-10-13T04:45:44.353 回答