全局名称“msg”未定义

时间:2014-02-01 02:43:57

标签: python-3.3

我正在编写一个名为SMS_store()的类。在其中,我有一个名为delete的方法。
 删除只是为了确保用户给了我一个有效的整数。如果是这样,它应该从列表中弹出一个项目。

class SMS_store():
      def __init__(self):
           self.__inbox = []

def delete(self, i):
    if i >= len(self.__inbox):
         return None
    else:
         self.__inbox.pop[i]

每当我在测试程序中运行代码时,我在删除阶段遇到两个错误:

1)如果我在列表中只有2个项目的时候输入myInbox.delete(2),我会得到“列表索引超出范围”,但我保护我免受该错误的影响。 myInbox.delete(3)给我无。

2)如果我在列表中存在有效索引1时键入myInbox.delete(1),则表示未定义全局名称“msg”。我不明白为什么我会看到这个错误
这是我的完整课程代码。

#SMS_store class
"""
Pre-condition:  SMS_store class is instantiated in client code.
Post-condition:  SMS_store class is instantiated.
"""

class SMS_store():
    #Object instantiation
    """
    Pre-conditon:  SMS_store class is instantiated in client code.
    Post-condition:  Object creates an empty list.

    """
    def __init__(self):
        self.__inbox = []

    #add_new_arrival method
    """
    Pre-condition:  Class method is handed a valid phone number of 11, 10, or 7
    digits as a string with no hyphens or letters, a string containing a time,
    and a string containing the text of a message.
    Post-condition:  Method will append a tuple containing False for an
    undread message, the phone number, the time arrived and the text of the
    message to the class created list.

    """
    def add_new_arrival(self, from_number, time_arrived, text_of_SMS):
        number = from_number

        #Check for valid phone number and add hyphens based on number length
        if len(number) == 11:
            number = number[0] + "-" + number[1:4] + "-" + number[4:7] + "-"\
                     + number[7:]
        elif len(number) == 7:
            number = number[:3] + "-" + number[3:]
        elif len(number) == 10:
            number = "1-" + number[:3] + "-" + number[3:6] + "-" + number[6:]
        elif number.isalpha():
            number = "Invalid number"
        else:
            number = "Invalid number"

        time = time_arrived
        text = text_of_SMS
        message = (False, number, time, text)
        self.__inbox.append(message)

    #message_count method
    """
    Post-condition:  method returns the number of tuples in class created list.
    Returns None if list is empty.

    """
    def message_count(self):
        count = len(self.__inbox)
        if count == 0:
            return None
        else:
            return count

    #get_unread_indexes method
    """
    Post-condition:  method creates an empty list,checks for any tuples with
    "False" at index 0.  If "False" is found, it appends the index for the
    tuple in the list.  Method returns list of indexes.

    """
    def get_unread_indexes(self):
        unread = []
        for message in self.__inbox:
            if message[0] == False:
                unread.append(self.__inbox.index(message))
        return unread

    #get_message method
    """
    Pre-condition:  Method is passed an integer.  
    Post-condition:  Method checks for a valid index number.  If valid, the
    method will then check if indexed tuple contains "True" or "False" at index
    0.  If True, message is returned in new tuple containing items from indexes
    1, 2, and 3.  If False, a new tuple is created containing "True"
    indicating the message is now read, plus indexes 1, 2, and 3 from the
    original called tuple.

    """
    def get_message(self, i):
        #check for valid index number
        if i >= len(self.__inbox):
            return None
        else:
            msg = self.__inbox[i]
            if msg[0] == True:
                return (msg[1], msg[2], msg[3])
            #create new tuple with True, and index 1-3 from original tuple
            else:
                self.__inbox.pop(i)
                newMsg = (True, msg[1], msg[2], msg[3])
                self.__inbox.insert(i, newMsg)
                return newMsg[1:]


    #delete method
    """
    Pre-condition:  Method is passed an integer.
    Post-condition:  Method checks that the integer is a valid index number. If
    valid, method pops index from class created list.

    """
    def delete(self, i):
        if i >= len(self.__inbox):
             return None
        else:
             self.__inbox.pop(i)


    #Clear method
    """
    Post-condition:  method resets the inbox to an empty list.

    """
    def clear(self):
        self.__inbox = []

以下是我在测试程序中使用代码的方法:

    #Test instantiation
    naomisInbox = SMS_store()
    martisInbox = SMS_store()

    #Test add_new_arrival
    naomisInbox.add_new_arrival("12345678912", "10:38PM", "Yay!  Sorry, been")
    martisInbox.add_new_arrival("23456789123", "10:37PM", "Hey I finally hit 90")
    martisInbox.add_new_arrival("12345678912", "10:40PM", "Now I sleep :)")
    naomisInbox.add_new_arrival("23456789123", "10:40PM", "Night")

    #Test message_count
    count = naomisInbox.message_count()
    print("Naomi has", count, "messages in her inbox.")
    count = martisInbox.message_count()
    print("Marti has", count, "messages in his inbox.\n")

    #Test get_unread_indexes
    numUnread = naomisInbox.get_unread_indexes()
    print("Naomi has unread messages at indexes: ", numUnread)
    numUnread = martisInbox.get_unread_indexes()
    print("Marti has unread messages at indexes: ", numUnread,"\n")

    #Test get_message
    msg = naomisInbox.get_message(9)
    print("Getting message from Naomi's inbox at index [9]: ")  
    if msg == None:
        print("No message at that index.")
    else:
        for item in msg:
            print(item)
    print("\n")
    numUnread = naomisInbox.get_unread_indexes()
    print("Naomi now has unread messages at indexes: ", numUnread, "\n") 
    msg = martisInbox.get_message(1)
    print("Getting message from Marti's inbox at index [1]:") 
    for item in msg:
        print(item)
    print("\n")
    numUnread = martisInbox.get_unread_indexes()
    print("Marti now has unread messages at indexes: ", numUnread, "\n")

    #Test delete
    remove = naomisInbox.delete(0)
    if remove == None:
          print("Invalid index.")
    count = naomisInbox.message_count()
    numUnread = naomisInbox.get_unread_indexes()
    print("Naomi now has", count, "messages with unread messages at index: ",\
          numUnread)


    #Test clear
    print("\nAfter clearing: ")
    naomisInbox.clear()
    count = naomisInbox.message_count()
    print("Naomi now has", count, "messages in her inbox.")
    martisInbox.clear()
    count = martisInbox.message_count()
    print("Marti now has", count, "messages in his inbox.")


错误

Error:
Traceback (most recent call last):
  File "/home/theriddler/Documents/CSIS153/Assignments/Nansen3/Nansen3.py", line 56, in <module>
    remove = naomisInbox.delete(0)
  File "/home/theriddler/Documents/CSIS153/Assignments/Nansen3/modSMS.py", line 125, in delete
NameError: global name 'msg' is not defined

感谢任何帮助。对不起,如果这是一个重复的问题。谢谢,布莱克威尔。

1 个答案:

答案 0 :(得分:0)

第一个问题。

1)如果列表中只有两个项目,那么你不能通过将2作为索引来删除第二个项目,它应该是1。

2)您的第二个问题告诉您在msg类中使用相同的SMS_store变量,而不将其定义为类的self变量。但是暂时找不到任何东西。您应该再次检查它,因为它在我的机器上运行良好。

现在对delete方法有所了解:

def delete(self, i):
    if i >= len(self.__inbox):
         return None
    else:
         self.__inbox.pop(i)

这里如果你想删除最后一条消息,那么只需使用self.__ibox.pop()而不传递任何索引,但是如果你想删除索引消息,那么你应该self.__ibox.pop(i-1)

因为如果i是列表的最后一个元素,那么它将始终等于列表的长度,并且永远不会执行else

此外,您的删除方法仅在None条件下返回if,但如果else运行,则默认返回None

remove = naomisInbox.delete(0)
if remove == None:
      print("Invalid index.")

即使消息被删除,也会始终将“无效索引”打印为消息。