[英]Python class instances stored in a list to store seperate instances
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?")
As seen above in the comment section i want to a list to store information from VARIOUS instances. 如上面的注释部分所示,我想要一个列表来存储来自各种实例的信息。 Not one instance, but SEVERAL seperate instances of information and the list being a list that is accessible and in which I can edit it and it SAVES the information from different instances. 不是一个实例,而是几个单独的信息实例,该列表是可访问的列表,我可以在其中进行编辑,并且可以从其他实例中保存信息。 Its not doing this. 它没有这样做。 It is resetting after every instance. 在每个实例后都会重置。
I have tried the global variable route but not understanding it and dont think it will work. 我尝试过全局变量路由,但不了解它,也不认为它将起作用。 I have set a global variable OUTSIDE the class and created an object inside the class to store in the list but it gives me an error: UnboundLocalError: local variable 'message_count' referenced before assignment . 我在类之外设置了一个全局变量,并在该类内部创建了一个对象以存储在列表中,但它给我一个错误: UnboundLocalError:赋值之前引用了局部变量'message_count' 。
I am working on an excercise that requires one to use classes in the interactive python site: http://openbookproject.net/thinkcs/python/english3e/classes_and_objects_I.html#term-class 我正在从事一项要求在交互式python网站中使用类的练习: http : //openbookproject.net/thinkcs/python/english3e/classes_and_objects_I.html#term-class
Please please help me. 请帮帮我。
You should not create a new instance of sms_store each time: 您不应每次都创建一个新的sms_store实例:
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 效果很好
It looks like you want a class variable. 看起来您想要一个类变量。
The code should look like this: 该代码应如下所示:
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
This way, the variables store
and message_count
will be shared by all the instances of the Sms_store
class. 这样,变量store
和message_count
将由Sms_store
类的所有实例共享。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.