带类的对象位置(Python)

2024-06-26 10:17:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: namenamesmaindeflinefindgenderyear
1条回答
网友
1楼 · 发布于 2024-06-26 10:17:31

向类中添加^{}^{}方法:

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()表示以及在列表和其他容器中显示对象时。你知道吗

相关问题 更多 >