Python global variable and class functionality

前端 未结 3 1484
野的像风
野的像风 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:46

    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.

    0 讨论(0)
  • 2021-01-05 05:47

    You are trying to assign to a global variable message_count without declaring it as such:

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

    Try to avoid using globals, or at least encapsulate the variable as a class attribute:

    class sms_store:
        message_count = 0
        store = []
    
        def add_new_arrival(self,number,time,text):
            sms_store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
            sms_store.message_count += 1
    

    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:

    class SMSStore(object):
        def __init__(self):
            self.store = []
            self.message_count = 0
    
        def add_new_arrival(self, number, time, text):
            self.store.append('From: {}, Received: {}, Msg: {}'.format(number, time, text))
            self.message_count += 1
    

    You are then free to create one instance and use that as a global if needs be:

    sms_store = SMSStore()
    

    Other code just uses sms_store.add_new_arrival(...), but the state is encapsulated in one instance.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题