0

当我打印出前 20 次出现的列表时,我得到的只是对象位置,而不是我需要的实际数据。此外,如果您有任何改进的想法,将不胜感激。请帮忙。谢谢。

这是我的代码。

class topList():
    __slots__ = ( "name", "gender", "occurences" )

def mkList( name, gender, occurences ):
    find = topList()
    find.name = name
    find.gender = gender
    find.occurences = occurences
    return find

def main():
    year = input( 'Enter year: ' )
    file = open( 'yob' + year + '.txt' )
    lst = []
    femaleLst = []
    maleLst = []
    for line in file:
        line = line.strip().split( "," )
        names = mkList( line[0], line[1], line[2] )
        lst.append( names )
        if names.gender == 'F':
            femaleLst += [ line ]
        else:
            maleLst += [ line ]
    while len( lst ) < 20:
        male = maleLst.pop()
        female = femaleLst.pop()
        if maleLst.occurences > femaleLst.occurences:
            lst += [ male ]
        else:
            lst += [ female ]
    print( lst[ : 20] )

main()
4

1 回答 1

2

向您的类添加__repr____str__方法:

class topList():
    __slots__ = ( "name", "gender", "occurences" )

    def __repr__(self):
        return 'topList({s.name!r}, {s.gender!r}, {s.occurences!r})'.format(s=self)

    def __str__(self):
        return '{s.name} ({s.gender}): {s.occurences!r})'.format(s=self)

演示:

>>> class topList():
...     __slots__ = ( "name", "gender", "occurences" )
...     def __str__(self):
...         return 'topList({s.name!r}, {s.gender!r}, {s.occurences!r})'.format(s=self)
... 
>>> tl = topList()
>>> tl.name = 'FooBar'
>>> tl.gender = 'm'
>>> tl.occurences = 42
>>> print(tl)
FooBar (m): 42
>>> tl
topList('FooBar', 'm', 42)

__str__当您的对象转换为字符串时,该方法会自动调用,就像print()函数一样。

__repr__方法用于repr()表示以及当您的对象显示在列表和其他容器中时。

于 2013-10-12T19:20:02.513 回答