在此示例中,如何将新对象附加到列表中?

时间:2017-10-04 03:09:57

标签: python

每当创建一个类的实例时,我想将该对象追加到另一个对象所持有的对象列表中。

class Something:
    def __init__(self):
        self.canvas = []
    def create_bum(self, name):
        MyInstance(name)
    def spank_all(self):
        for butt in self.canvas:
            print ("You spanked " + butt.name)

class MyInstance:
    def __init__(self, name):
        self.name = name
        Something.canvas.append(self) # How do I do this?

foo = Something()
foo.create_bum("bob")
foo.create_bum("alice")
foo.spank_all()

1 个答案:

答案 0 :(得分:2)

你大部分都是正确的,只是错误的一行。将create_bum函数修改为如下所示:

def create_bum(self, name):
    self.canvas.append(MyInstance(name))

然后,您可以从MyInstance班级__init__功能中删除以下一行:

Something.canvas.append(self)