Code: Alles auswählen
class Container:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
item.parent = self
def remove_item(self, item):
self.items.remove(item)
item.parent = None
Code: Alles auswählen
class ListRelation(object):
def __init__(self, parent, child_attr=None):
self.parent, self.child_attr = parent, child_attr
self.children = []
def add(self, child):
self.children.append(child)
self.set_child_attr(child, self.parent)
def remove(self, child):
self.children.remove(child)
self.se_child_attr(child, None)
def __len__(self):
return len(self.children)
def __iter__(self):
return iter(self.children)
def __getitem__(self, index):
return self.children[index]
def __setitem__(self, index, value):
self.set_child_attr(self.children[index], None)
self.children[index] = value
self.set_child_attr(value, self.parent)
def __delitem__(self, index):
self.set_child_attr(self.children[index], None)
del self.children[index]
def set_child_attr(self, child, parent):
if self.child_attr: setattr(child, self.child_attr, parent)
def filter(self, fn):
return (child for child in self.children if fn(child))
Code: Alles auswählen
class Container:
def __init__(self):
self.items = ListRelation(self, 'parent')