繁体   English   中英

自变量在类中更改不返回

[英]self variable changed in class not returning

我尝试使用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但没有,我不理解。

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

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

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())

由于您的收件箱类基本上是列表的包装器,因此您可以使其成为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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM