如何使用python在循环内创建具有不同名称的对象?

时间:2013-10-13 04:42:48

标签: python loops object

该问题的答案是否有效,或者我已经读过你不需要实际命名它们......所以我试过这个:

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

任何帮助?

1 个答案:

答案 0 :(得分:1)

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

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