每当创建一个类的实例时,我想将该对象追加到另一个对象所持有的对象列表中。
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()
答案 0 :(得分:2)
你大部分都是正确的,只是错误的一行。将create_bum
函数修改为如下所示:
def create_bum(self, name):
self.canvas.append(MyInstance(name))
然后,您可以从MyInstance
班级__init__
功能中删除以下一行:
Something.canvas.append(self)