在Python中创建列表对象类

时间:2013-07-04 04:21:56

标签: python list class append

这是一个基本问题。我正在尝试以下代码:

class SMS_store:

def __init__(self):
    self=[]    #probably something is wrong here

def add_new_arrival(self,from_number,time_arrived,text_of_SMS):
    self.append([False,from_number,time_arrived,text_of_SMS])    #append list to self list
    self[len(self)-1]=tuple(self[len(self)-1])

def message_count(self):
    return len(self)

my_inbox=SMS_store()
my_inbox.add_new_arrival('01234','9:37 AM','How are you?')

但是我收到以下错误:

>>> 
Traceback (most recent call last):
  File "C:\Users\Arnob\Desktop\New Text Document.py", line 15, in <module>
    my_inbox.add_new_arrival('01234','9:37 AM','How are you?')
  File "C:\Users\Arnob\Desktop\New Text Document.py", line 8, in add_new_arrival
    self.append([False,from_number,time_arrived,text_of_SMS])    #append list to self list
AttributeError: 'SMS_store' object has no attribute 'append'
>>>

我的代码有什么问题?

3 个答案:

答案 0 :(得分:4)

如果您想继承list,请使用以下内容:

class SMS_store(list):
               ^^^^^^

并从self方法中删除__init__的分配。

也就是说,您可能只想拥有一个包含列表的命名属性:

class SMS_store(object):

   def __init__(self):
      self.messages = []

   def add_new_arrival(self, from_number, time_arrived, text_of_SMS):
      self.messages.append((False,from_number,time_arrived,text_of_SMS))

   def message_count(self):
      return len(self.messages)

my_inbox = SMS_store()
my_inbox.add_new_arrival('01234','9:37 AM','How are you?')

就代表实际消息而言,这听起来像是namedtuple的一个很好的用例。它就像一个元组,但允许按名称访问字段。这是一个快速说明:

import collections

SMS = collections.namedtuple('SMS', 'from_number time_arrived text_of_SMS')

sms = SMS(from_number='01234', time_arrived='9:37 AM', text_of_SMS='How are you?')
print sms.text_of_SMS

答案 1 :(得分:3)

您可以像这样<{p>}继承list

class SMS_store(list):

    def add_new_arrival(self, from_number, time_arrived, text_of_SMS):
        self.append((False, from_number, time_arrived, text_of_SMS))    #append tuple to self

    def message_count(self):
        return len(self)

请注意,除非您希望在那里做额外的事情,否则不需要__init__

您无需附加列表然后将其转换为元组,您可以使用()代替[]直接创建元组

答案 2 :(得分:2)

您仍然需要创建一个普通的变量名称,只需将self.作为前缀:

self.mylist = []

要访问它,您可以执行以下操作:

self.mylist.append(n)

或者:

self.mylist[3] = 'hi'

你实际上是在覆盖self。你不想这样做。