在python中调用列表中的特定对象?

时间:2016-12-05 09:57:43

标签: python list oop

我已经定义了以下内容:

class SMSMessage(object):

  def __init__(self, hasBeenRead, messageText, fromNumber):
      self.hasBeenRead = hasBeenRead
      self.messageText = messageText
      self.fromNumber = fromNumber

hasBeenRead = "False"
fromNumber = "07189202003"

具有以下功能:

def MarkAsRead(self):
    if hasBeenRead == "False":
        return hasBeenRead == "True"

def add_sms():
    sms1 = (hasBeenRead, messageText, fromNumber)
    return SMSStore.append(sms1)

def get_count():
    return len(SMSStore)

def get_message(i):
    for i in SMSStore:
    return messageText

def get_unread_messages(i):
    for i in SMSStore:
        if hasBeenRead == "False":
           return messageText

这是SMS模拟的逻辑,用户打算将消息发送到列表(SMSStore []),然后从列表中调用特定消息:

userChoice = ""

while userChoice != "quit":
    userChoice = raw_input("What would you like to do - read/send/quit?")

    if userChoice == "read":
        unreadChoice = raw_input("Would you like to retrieve all unread messages or one of your own choice? - all unread/custom  ")

        if unreadChoice == "custom":
            messageNo = int(raw_input("Please enter which messsage number you want to read: "))
            print get_message(messageNo)
            print MarkAsRead(messageNo)


        elif unreadChoice == "all unread":
            print get_unread_messages(hasBeenRead)

        else:
            print "incorrect entry"

    elif userChoice == "send":
        messageText = raw_input('Please type in your message')
        add_sms()

        print SMSStore

我的主要问题是我能够将(hasBeenRead,messageText,fromNumber)发送到SMSStore但是在尝试阅读时我似乎无法返回用户选择的messageNo的messagetext。它总是返回列表中最后一项的messageText。我还是编码的新手,所以任何帮助都会非常感激。

谢谢

1 个答案:

答案 0 :(得分:0)

我不确定SMSStore的作用是什么,但这段代码看起来很可疑:

def get_message(i):
    for i in SMSStore:
    return messageText

为什么要迭代SMSStore而只是返回messageText?那会是一个缺少的缩进吗?