使用 __str__ 到 return 可变数量的不同内衬字符串?

Using __str__ to return a variable number of different lined strings?

我正在做一个在 Python 3.x 中创建 "Facebook" 的项目。我目前坚持的部分是使用 str 函数来 return 不同行上的字符串。

我为此使用的代码是:

class Status:
    likers = []
    commentObjs = []
    def __init__(self, statusPoster, statusMsg, likers, commentObjs):
        self.statuser = statusPoster
        self.status = statusMsg
        self.likers = likers
        self.commentObjs = commentObjs

def __str__(self):
    return '%s: %s \n"hello"' %(self.statuser,self.status)

__repr__= __str__

我 运行 遇到的问题是可以有可变数量的点赞者和可变数量的 commentObjs。

如果只有一个值,我必须执行什么才能做到这一点,例如:

likers = ["Spongebob"] 
commentObjs = ["Spongebob: You should watch the Spongebob movie!"]

它 return 在终端中:

Brad Pitt will watch a movie today!
Spongebob likes this.
Spongebob: You should watch The Spongebob movie!

但是如果每个列表中的值不止一个,比如:

likers = ["Spongebob","Harry Potter"] 
commentObjs = ["Spongebob: You should watch the Spongebob movie!","Brad Pitt: How about nah?"]

它returns:

Brad Pitt will watch a movie today!
Spongebob, Harry Potter likes this.
Spongebob: You should watch The Spongebob movie!
Brad Pitt: Nah, I will probably watch Mr and Mrs. Smith.

我能想到的唯一可能做到这一点的方法是使用 for 循环和 len(likers),但我不知道如何在 return 的情况下做到这一点正在处理名称和状态的常量值。

您正在这里寻找 str.join()。这使您可以连接多个字符串,中间有一个连接字符串(可以为空):

>>> likers = ['Spongebob', 'Harry Potter']
>>> ', '.join(likers)
'Spongebob, Harry Potter'
>>> ' -> '.join(likers)
'Spongebob -> Harry Potter'

您可能还想了解 str.format() 将值插入模板字符串:

def __str__(self):
    likers = ', '.join(self.likers)
    comments = '\n'.join(self.commentObjs)
    return '{} {}\n{} likes this.\n{}'.format(
        self.statuser, self.status, likers, comments)

这将用逗号连接您的 likers 值,并用换行符连接评论。

您不应该将其用作您的 __repr__;应该会产生 debugging 输出,帮助您区分 class 的两个实例,可选择包含该输出的值部分。