Im creating a simple python program that gives basic functionality of an SMS_Inbox. I have created an 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 i > len(store-1):
print("Index does not exist")
else:
del store[i]
message_count -= 1
In the bolded bit I am getting an error:
UnboundLocalError: local variable 'message_count' referenced before assignment.
I created a global variable store which is an empty list and this works when I use the add_new_variable object. However for some reason it is not adding values to my global message_count variable.
Please help
You are trying to assign to a global variable
message_count
without declaring it as such:Try to avoid using globals, or at least encapsulate the variable as a class attribute:
However, your class instances have no state anymore, so there is no point in creating a class here. It only serves to confuse your purpose.
Either store state in instances, or use global functions (so don't use a class at all); the former is preferable to the latter.
Transforming your setup to a class whose instances hold state, using proper PEP-8 styleguide naming and string formatting:
You are then free to create one instance and use that as a global if needs be:
Other code just uses
sms_store.add_new_arrival(...)
, but the state is encapsulated in one instance.If the variable you are referring to is
message_count
, the error is because in Python, you have to specify a variable asglobal
before you can make edits with it.This should work.
As written above, you'd be better off encapsulating it in the
__init__
function instead of declaring itglobal
.That's not how classes work. Data should be stored within the class instance, not globally.