Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #19565

object aware of others

Date 2012-01-29 16:48 +1300
Subject object aware of others
From Lee Chaplin <lchaplin13@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.5187.1327808922.27778.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

object aware of others Lee Chaplin <lchaplin13@gmail.com> - 2012-01-29 16:48 +1300
  Re: object aware of others Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-01-29 04:13 +0000

csiph-web