我正在做一个用python3.x创建“Facebook”的项目,我目前所做的是使用str函数返回不同行上的字符串。在
我使用的代码是:
class Status:
likers = []
commentObjs = []
def __init__(self, statusPoster, statusMsg, likers, commentObjs):
self.statuser = statusPoster
self.status = statusMsg
self.likers = likers
self.commentObjs = commentObjs
以及
^{pr2}$我遇到的问题是likers的数量和commentobj的数量是可变的。在
如果只有一个值,例如:
likers = ["Spongebob"]
commentObjs = ["Spongebob: You should watch the Spongebob movie!"]
它在终端返回:
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?"]
它返回:
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)
,但我不知道如何在返回名称和状态的常量值的同时做到这一点。在
你在这里找^{} 。这允许您使用连接字符串连接多个字符串(可以为空):
您可能还想了解^{} 如何将值插值到模板字符串中:
^{pr2}$这将用逗号连接您的
likers
值,并用换行符将注释连接起来。在您不应该将其用作您的
__repr__
;这样会产生调试输出,从而帮助您区分类的两个实例,可以选择使用输出中包含的值部分。在相关问题 更多 >
编程相关推荐