Python global variable and class functionality

前端 未结 3 1514
野的像风
野的像风 2021-01-05 05:24

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 sm         


        
3条回答
  •  情深已故
    2021-01-05 05:57

    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
    

提交回复
热议问题