Python global variable and class functionality

前端 未结 3 1509
野的像风
野的像风 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.

提交回复
热议问题