user2318861
user2318861

Reputation: 131

Python class instances stored in a list to store seperate instances

from datetime import datetime

class sms_store:
    def __init__(self):
        self.store = [] #Keeps resetting / not saving data from previous instances
        self.message_count = 0 #Keeps resetting / not saving data from previous instances
    def add_new_arrival(self,number,time,text):
        self.store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
        self.message_count += 1

newsms = sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms.add_new_arrival("23456",time, "hello, how are you?")

As seen above in the comment section i want to a list to store information from VARIOUS instances. Not one instance, but SEVERAL seperate instances of information and the list being a list that is accessible and in which I can edit it and it SAVES the information from different instances. Its not doing this. It is resetting after every instance.

I have tried the global variable route but not understanding it and dont think it will work. I have set a global variable OUTSIDE the class and created an object inside the class to store in the list but it gives me an error: UnboundLocalError: local variable 'message_count' referenced before assignment.

I am working on an excercise that requires one to use classes in the interactive python site: http://openbookproject.net/thinkcs/python/english3e/classes_and_objects_I.html#term-class

Please please help me.

Upvotes: 1

Views: 2283

Answers (2)

cmd
cmd

Reputation: 5830

You should not create a new instance of sms_store each time:

newsms = sms_store()
newsms.add_new_arrival("23456", datetime.now().strftime('%H:%M:%S'), "hello, how are you?")
newsms.add_new_arrival("65432", datetime.now().strftime('%H:%M:%S'), "I'm fine, thanks")

works just fine

Upvotes: 1

Ionut Hulub
Ionut Hulub

Reputation: 6326

It looks like you want a class variable.

The code should look like this:

from datetime import datetime

class Sms_store:
    store = []
    message_count = 0

    def __init__(self):
        pass

    def add_new_arrival(self,number,time,text):
        Sms_store.store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
        Sms_store.message_count += 1

newsms1 = Sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms1.add_new_arrival("23456",time, "hello, how are you?")

newsms2 = Sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms2.add_new_arrival("23456",time, "hello, how are you?")

print Sms_store.store

This way, the variables store and message_count will be shared by all the instances of the Sms_store class.

Upvotes: 0

Related Questions