自变量在类中更改不返回

时间:2018-10-10 17:14:43

标签: python python-3.x

我尝试使用len(self.inbox)返回包含元组的列表中有多少个元素,但是,我无法使其正常工作,因此我试图在使用新的元素被添加到inbox列表中,它将添加一个元素到x中,基本上将扮演len()的角色。

class inbox:
    """Inbox class:
       add_new_arrival, message_count, get_unread_indexes, get_message, delete, clear"""
    def __init__(self):
        self.inbox = []
        self.x = 0

    def add_new_arrival(self, from_number, time_arrived, text_of_SMS):
        # Makes new SMS tuple, inserts it after other messages in the store.
        # When creating this message, its has_been_viewed status is set to False.
        self.x += 1
        self.inbox.append(tuple([from_number, time_arrived, text_of_SMS, False]))

    def message_count(self):
        # Returns the number of sms messages in inbox
        return self.x

inbox().add_new_arrival("from number", "time arrived", "text")
print(inbox().message_count())

但是,当我运行该程序时,即使我用inbox().add_new_arrival(...)添加了一条新消息,最后的打印也会返回0。

它应该返回1,但不会,并且我不理解。

2 个答案:

答案 0 :(得分:1)

您正在收件箱类的新实例(message_count())上运行inbox(),该实例实例化了长度为零的收件箱。

您可以考虑根据需要使用该对象将收件箱类的实例分配给变量。

class inbox:
    """
    Inbox class: add_new_arrival, message_count, 
    get_unread_indexes, get_message, delete, clear
    """
    def __init__(self):
        self.inbox = []

    def add_new_arrival(self, from_number, time_arrived, text_of_SMS):
        # Makes new SMS tuple, inserts it after other messages in the store.
        # When creating this message, its has_been_viewed status is set to False.
        self.inbox.append(tuple([from_number, time_arrived, text_of_SMS, False]))

    def message_count(self):
        # Returns the number of sms messages in inbox
        return len(self.inbox)

my_inbox = inbox()
my_inbox.add_new_arrival("from number", "time arrived", "text")
print(my_inbox.message_count())

答案 1 :(得分:0)

由于收件箱类基本上是列表的包装器,因此可以将其设为UserList的子类,并可以访问所有列表方法。

from collections import UserList

class Inbox(UserList):
    """
    Inbox class: add_new_arrival, message_count, 
    get_unread_indexes, get_message, delete, clear
    """

    def add_new_arrival(self, from_number, time_arrived, text_of_SMS):
        """Makes new SMS tuple, inserts it after other messages in the store.
        When creating this message, its has_been_viewed status is set to False"""
        self.append((from_number, time_arrived, text_of_SMS, False))

my_inbox = Inbox()
my_inbox.add_new_arrival("from number", "time arrived", "text")
print(len(my_inbox))