8

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

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'
>>>

我的代码有什么问题?

4

3 回答 3

6

你可以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__请注意,除非您希望在那里做一些额外的事情,否则没有必要。

您不需要附加列表然后将其转换为元组,您可以直接创建元组()而不是[]

于 2013-07-04T04:26:15.640 回答
5

如果要继承自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
于 2013-07-04T04:25:27.827 回答
2

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

self.mylist = []

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

self.mylist.append(n)

或者:

self.mylist[3] = 'hi'

你实际上是压倒一切self的。你不想那样做。

于 2013-07-04T04:22:27.380 回答