469,646 Members | 1,100 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,646 developers. It's quick & easy.

Object instance "reporting" to a container class instance

I would like for an object to "report" to a container object when a
new instance is created or deleted. I could have a container object
that is called when a new instance is created, as below.

class AnyObject:
pass

class Container:
links = []
def add(self,other):
while other not in self.links:
self.links.append(other)
def rem(self,other):
while other in self.links:
self.links.remove(other)
....

container = Container()
a = AnyObject()
container.add(a)

My question is: can (should? :-) this "reporting" be done inside the
instance's __init__ and __del__ methods (that is, an instance
"reports" to the container as soon as it is created or deleted)?

Thanks!
Daniel

---

I'm working out a design where Object A is "linked" to Object B, and
both objects become aware of that relationship. I have implemented an
example successfully; the code is below. My main question is above,
but I would appreciate comments on the code! (For example, I'm
wondering whether my way of defining variables in the class but
assigning them locally to each instance (in the "Object.init" method)
is really a bad kludge...)
class Object():
def __del__(self):
print "buh-bye!", self # Verbose for understanding garbage cleanup
def init(self,name):
self.links = []
self.name = name
def add(self,other):
while other not in self.links:
self.links.append(other)
other.add(self)
def rem(self,other):
while other in self.links:
self.links.remove(other)
other.rem(self)

class Student(Object):
def __init__(self,name):
self.init(name)

class Section(Object):
def __init__(self,name):
self.init(name)

class Task(Object):
def __init__(self,name):
self.init(name)

## Construct test instances!

students = {}
for name in ['Jose','Daniel','Rusty']:
student = Student(name)
students[name] = student

sections = {}
for name in ['English 1']:
section = Section(name)
sections[name] = section

tasks = {}
for name in ['Homework 1','Exam 1','Homework 2','Exam 2']:
task = Task(name)
tasks[name] = task

# Display example connections
def show_connections():
for section in sections:
print sections[section].name
for link in sections[section].links:
print "\t", link.name

# Add some connections...

print "Now adding connections..."
for name in tasks:
sections['English 1'].add(tasks[name])
show_connections()

# Remove some connections...

print "Now removing connections..."
for name in tasks:
sections['English 1'].rem(tasks[name])
show_connections()

for task in tasks:
print tasks[task].links

for section in sections:
print sections[section].links

## Test garbage cleanup

sections['English 1'].add(tasks['Exam 1'])
print sections['English 1'].links
sections['English 1'].rem(tasks['Exam 1'])
del sections['English 1']
Mar 12 '07 #1
2 1810
Daniel Lipovetsky <da***************@gmail.comwrote:
I would like for an object to "report" to a container object when a
new instance is created or deleted. I could have a container object
that is called when a new instance is created, as below.

class AnyObject:
pass

class Container:
links = []
Why a class variable rather than a normal instance variable?
def add(self,other):
while other not in self.links:
self.links.append(other)
What a weird implementation... why the while, &c?!
def rem(self,other):
while other in self.links:
self.links.remove(other)
Ditto.
...

container = Container()
a = AnyObject()
container.add(a)

My question is: can (should? :-) this "reporting" be done inside the
instance's __init__ and __del__ methods (that is, an instance
"reports" to the container as soon as it is created or deleted)?
The object's __del__ will never be called, because the object's presence
in the Container's self.links will always keep the object alive.

Study weak references -- and make the Container's links (whether it
needs to be a class or instance variable for the container) a
weakref.WeakValueDictionary (as keys, use unique, always-incrementing
integers) -- a WeakKeyDictionary is OK too if contained objects are
hashable by identity (and might make other things easier, e.g. moving an
object from one container to another by removing it from one and adding
it from the other).

With weak references, the "reporting" of the object's demise will be
automatic and transparent - the relevant dict entry just disappears when
the object does. For the "registration", the call to the add method of
the container, it's fine to do it in __init__ if at contained-object's
init time you already know, invariably, what container it will be in.
Alex
Mar 12 '07 #2
Daniel Lipovetsky wrote:
I would like for an object to "report" to a container object when a
new instance is created or deleted. I could have a container object
that is called when a new instance is created, as below.
I've run into a similar problem before, in my case it was easiest to
allow the container to create the new instances, sort of like:

<CODE>

class Something(object):
def __init__(self, *args):
self.x=args

class Container(object):
def __init__(self):
self.instances=[]

def newinstance(self, newclass, *args):
tmp=newclass(args)
self.instances.append(tmp)
return tmp

def delinstance(self, inst):
self.instances.remove(inst)
cont=Container()
a=cont.newinstance(Something, 5, 6)
b=cont.newinstance(Something, 7, 8)
c=cont.newinstance(Something, 8, 9)

print len(cont.instances)

cont.delinstance(b)
print len(cont.instances)

#note that b is still defined, unless you remove that name explicitly...
print b
del b
print b

</CODE>

This can be very, very, very ugly. I don't particularly actually
recommend doing anything like this. Usually you should re-think your
organization to make this unnecessary. I suppose, though, it can come in
handy in certain situations.

-Jordan G
Mar 12 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Rabun | last post: by
6 posts views Thread by Angelos | last post: by
10 posts views Thread by Lorenzo Di Gregorio | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.