Python global variable and class functionality -
im creating simple python program gives basic functionality of sms_inbox. have created sms_inbox method.
store = [] message_count = 0 class sms_store: def add_new_arrival(self,number,time,text): store.append(("from: "+number, "recieved: "+time,"msg: "+text)) **message_count += 1** def delete(self,i): if > len(store-1): print("index not exist") else: del store[i] message_count -= 1
in bolded bit getting error:
unboundlocalerror: local variable 'message_count' referenced before assignment.
i created global variable store empty list , works when use add_new_variable object. reason not adding values global message_count variable.
please help
that's not how classes work. data should stored within class instance, not globally.
class smsstore(object): def __init__(self): self.store = [] self.message_count = 0 def add_new_arrival(self,number,time,text): self.store.append(("from: "+number, "recieved: "+time,"msg: "+text)) self.message_count += 1 def delete(self, i): if >= len(store): raise indexerror else: del self.store[i] self.message_count -= 1 sms_store = smsstore() sms_store.add_new_arrival("1234", "now", "lorem ipsum") try: sms_store.delete(20) except indexerror: print("index not exist") print sms_store.store # multiple separate stores sms_store2 = smsstore() sms_store2.add_new_arrival("4321", "then", "lorem ipsum") print sms_store2.store