472,961 Members | 2,233 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,961 software developers and data experts.

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 1929
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Bill MacLean | last post by:
-- Example Schema posted at end of message: --- For reporting purposes, I need to build a single comma delimited string of values from the "many" table of a database. The easiest way to see...
0
by: trint | last post by:
How can I call a report created from reporting services in my c#.net (visual studio .net 2003) project? Thanks, Trint
3
by: Rabun | last post by:
Heres one that is giving me fits ( = = Access newbie), more than likely something simple that I blew right over . . . any help is appreciated - I have a report based on a query, with several...
2
by: Fish | last post by:
I have been researching the correct way to organize my solution so that it makes best use of VB.NET inherent ability to manage resources such as objects. My solution contains 2 projects and the...
6
by: Angelos | last post by:
Hello again, I have written three classes : validate.class.php, report_handler.class.php, sentry.class.php. The problem is that the "validate" class uses the "reporting" class and the...
0
by: YellowFin Announcements | last post by:
Whitepaper: "Yellowfin Reporting" enables Embedded Business Intelligence -------------------------------------------------------------------------------- Embedded reports are a standard...
10
by: Lorenzo Di Gregorio | last post by:
Hello, I've been using Python for some DES simulations because we don't need full C speed and it's so much faster for writing models. During coding I find it handy to assign a variable *unless...
12
by: Robert Fuchs | last post by:
Hello, This example: public class BaseC { public int x; public void Invoke() {} } public class DerivedC : BaseC
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.