带类的对象位置(Python)

时间:2013-10-12 19:18:07

标签: python python-3.x

当我打印出前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()

1 个答案:

答案 0 :(得分: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()表示,当您的对象显示在列表和其他容器中时。