self destruction :)
Jonathan Hogg
jonathan at onegoodidea.com
Fri Jun 28 06:08:36 EDT 2002
On 28/6/2002 10:37, in article 3d1c2d6a$0$231$4d4ebb8e at news.nl.uu.net,
"Guyon Morée" <gumuz at looze.net> wrote:
> yep this is actually what i mean, but the problem is is that this action
> should come from the object within the list. this is object 'knows' when
> it's done, the list doesn't
>
> see my problem?
I going to assume that the list is in an instance of some class and that it
points to things that are instances of some other class. My solution would
look something like:
-----
class Parent:
def __init__( self ):
self._children = []
def add_child( self, child ):
assert child not in self._children
self._children.append( child )
child.take_parent( self )
def remove_child( self, child ):
assert child in self._children
child.lose_parent()
self._children.remove( child )
def items( self ):
return self._children
class Child:
def __init__( self, x ):
self._x = x
self._parent = None
def __repr__( self ):
return '<Child %s>' % `self._x`
def take_parent( self, parent ):
if self._parent:
parent = self._parent
self._parent = None
parent.remove_child( self )
self._parent = parent
def lose_parent( self ):
self.take_parent( None )
-----
Which then works like so:
>>> p = Parent()
>>> c1 = Child(1)
>>> c2 = Child(2)
>>> c1
<Child 1>
>>> c2
<Child 2>
>>> p.add_child( c1 )
>>> p.add_child( c2 )
>>> p.items()
[<Child 1>, <Child 2>]
>>> c1.lose_parent()
>>> p.items()
[<Child 2>]
>>>
You can write something much more clever than this. I'm a fan of abstracting
out this sort of behaviour into classes that you can mixin to any class. I
usually use a "broadcaster/listener" pattern allowing children to notify
their parents of their imminent demise.
Jonathan
More information about the Python-list
mailing list