object aware of others

L

Lee Chaplin

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()
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
 
S

Steven D'Aprano

On Sun, 29 Jan 2012 16:48:34 +1300, Lee Chaplin wrote:

[...]
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:

globals() is not actually global to the entire Python session. It
actually means global to a module. Every module has its own globals().

Python doesn't really have a concept of "global to the entire session" as
such, although the built-ins comes close. But if you mess with built-ins,
people will be sarcastic at you. They may even use irony.

However, you can fetch another module's globals by using:

vars(module)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top