object aware of others

Lee Chaplin lchaplin13 at gmail.com
Sat Jan 28 22:48:34 EST 2012


Hi all,

I am trying to create an object that is aware of other objects created
before itself, and when found, then copy some attributes from them,
something like:

class A:
    def __init__(self):
        self.myname = "IamA"
        print 'This is A'
    def foo(self):
        print "foo"
    def update(self):
        i = ''
        obj = self
        for i in globals():
            obj = globals()[i]
            if hasattr(obj, 'myname'):
                print "The only friends I've got are ", i, obj.myname
            else:
                print "Oops, not my friend."


class B:
    def __init__(self):
        print 'This is B'
    def foo(self):
        print "bar"

# a = A()
# b = B()
# c = A()
# c.update()

The last four lines work if they are in the same module as the class
definitions (a000), but it doesn't work if they are called from a
different module, say:

import a000

a = a000.A()
b = a000.B()
c = a000.A()
c.update()

I presume there is something that need to replace the globals() call,
but I cannot find what.
Any help is greatly appreciated.

Thanks,
Lee



More information about the Python-list mailing list