1
from datetime import datetime

class sms_store:
    def __init__(self):
        self.store = [] #Keeps resetting / not saving data from previous instances
        self.message_count = 0 #Keeps resetting / not saving data from previous instances
    def add_new_arrival(self,number,time,text):
        self.store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
        self.message_count += 1

newsms = sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms.add_new_arrival("23456",time, "hello, how are you?")

如上面评论部分所示,我想要一个列表来存储来自各种实例的信息。不是一个实例,而是几个单独的信息实例,列表是一个可访问的列表,我可以在其中编辑它,它保存来自不同实例的信息。它不这样做。它在每个实例后重置。

我已经尝试过全局变量路由但不理解它并且不认为它会起作用。我在类外设置了一个全局变量,并在类内创建了一个对象以存储在列表中,但它给了我一个错误:UnboundLocalError: local variable 'message_count' referenced before assignment

我正在做一项需要在交互式 python 站点中使用类的练习:http: //openbookproject.net/thinkcs/python/english3e/classes_and_objects_I.html#term-class

请帮帮我。

4

2 回答 2

1

You should not create a new instance of sms_store each time:

newsms = sms_store()
newsms.add_new_arrival("23456", datetime.now().strftime('%H:%M:%S'), "hello, how are you?")
newsms.add_new_arrival("65432", datetime.now().strftime('%H:%M:%S'), "I'm fine, thanks")

works just fine

于 2013-04-25T15:46:23.577 回答
0

看起来你想要一个类变量。

代码应如下所示:

from datetime import datetime

class Sms_store:
    store = []
    message_count = 0

    def __init__(self):
        pass

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

newsms1 = Sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms1.add_new_arrival("23456",time, "hello, how are you?")

newsms2 = Sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms2.add_new_arrival("23456",time, "hello, how are you?")

print Sms_store.store

这样,变量storemessage_countSms_store类的所有实例共享。

于 2013-04-25T15:25:23.460 回答