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


Groups > comp.lang.python > #19565 > unrolled thread

object aware of others

Started byLee Chaplin <lchaplin13@gmail.com>
First post2012-01-29 16:48 +1300
Last post2012-01-29 04:13 +0000
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  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

#19565 — object aware of others

FromLee Chaplin <lchaplin13@gmail.com>
Date2012-01-29 16:48 +1300
Subjectobject aware of others
Message-ID<mailman.5187.1327808922.27778.python-list@python.org>
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

[toc] | [next] | [standalone]


#19567

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-01-29 04:13 +0000
Message-ID<4f24c761$0$29968$c3e8da3$5496439d@news.astraweb.com>
In reply to#19565
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)


-- 
Steven

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web