Reputation: 15
I tried to use len(self.inbox)
before to return how many elements are in the list that holds the tuples, however, I couldn't get that to work, so I'm trying to make it so when a new element is added to inbox
list, it will add one to x
which will basically take the role of 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())
However, when I run the program, the print at the end will return 0, even though I add a new message with inbox().add_new_arrival(...)
.
It should return 1
but it doesn't, and I'm not understanding.
Upvotes: 0
Views: 43
Reputation: 23064
Since your inbox class is basically a wrapper around a list, you could make it a subclass of UserList and have access to all list methods.
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))
Upvotes: 0
Reputation: 2287
You are running message_count()
on a new instance of your inbox class (inbox()
), which is instantiated with an inbox of length zero.
You might consider assigning an instance of your inbox class to a variable, using that object as you need.:
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())
Upvotes: 1