在Python中创建嵌套列表类

0 投票
3 回答
2155 浏览
提问于 2025-04-17 02:47

我搞不清楚自己哪里出错了。我需要创建一个嵌套列表(也就是可能的解决方案),所以我创建了一个类,这个类可以把一个解决方案添加到现有解决方案的列表中(因为每个解决方案都是一个一个计算出来的)。

这个函数运行得很好:

def appendList(list):
    #print list
    list2.append(list)

x =0
while x < 10:
    x = x+1
    one = "one"
    two = "two"
    appendList([(one), (two)])

print list2

结果是:

[['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two']]

但是当我把这个完全相同的函数放到一个类里时,我却收到一个错误提示,内容是:

TypeError: appendList() takes exactly 1 argument (2 given)

这是我创建的类以及我如何调用它的:

class SolutionsAppendList:
    list2 = []
    def appendList(list):
    #print list
        list2.append(list)
appendList.appendList([('one'), ('two')])

我知道我肯定犯了一个很基础的错误,但我就是搞不清楚为什么,因为我在类里用的还是同样的函数。

如果有任何建议或意见,那就太好了。谢谢!

3 个回答

1

应该是:

class SolutionsAppendList:
    list2 = []
    def appendList(self, list):
    #print list
        self.list2.append(list)

类的方法总是应该把self(指向实例的引用)作为第一个参数。

2

在使用类的实例时,特殊变量 self 总是作为第一个参数传递给方法调用。你需要修改你的函数声明来适应这个规则:

class SolutionList:
  def appendList(self, list):
    #rest of your function here.
2

因为你在处理类,所以使用 实例变量 是很重要的。你可以通过 self 这个关键词来访问这些变量。如果你在使用类的方法,记得把第一个参数设为 self。所以,修改后的代码是...

class SolutionsAppendList:
    def __init__(self):
        self.list = []

    def appendList(self, list):
    #print list
        self.list.append(list)

这点很酷,因为你不再需要 list2 了。实例变量(self.list)和局部变量(你传给 appendList() 方法的 list)是不同的。编辑一下:我还添加了一个 __init__ 方法,这个方法在创建 SolutionsAppendList 对象的实例时会被调用。在我第一次回复的时候,我忽略了 self.* 在方法外是无法使用的。这里是修改后的代码(谢谢你,David)。

撰写回答