Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global variable and class functionality

Tags:

python

class

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

like image 833
user2318861 Avatar asked Apr 25 '13 08:04

user2318861


Video Answer


2 Answers

That's not how classes work. Data should be stored within the 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 i >= 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 does 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
like image 186
Eric Avatar answered Oct 01 '22 02:10

Eric


If the variable you are referring to is message_count, the error is because in Python, you have to specify a variable as global before you can make edits with it.

This should work.

store = []
message_count = 0
class sms_store:
    def add_new_arrival(self,number,time,text):
        global message_count
        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:
            global message_count
            del store[i]
            message_count -= 1

As written above, you'd be better off encapsulating it in the __init__ function instead of declaring it global.

like image 22
Sukrit Kalra Avatar answered Oct 01 '22 02:10

Sukrit Kalra