object aware of others

Discussion in 'Python' started by Lee Chaplin, Jan 29, 2012.

  1. Lee Chaplin

    Lee Chaplin Guest

    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
    Lee Chaplin, Jan 29, 2012
    #1
    1. Advertising

  2. 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
    Steven D'Aprano, Jan 29, 2012
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Maciej Sobczak
    Replies:
    5
    Views:
    303
    Maciej Sobczak
    Dec 23, 2003
  2. nutty
    Replies:
    6
    Views:
    381
    Tom Widmer
    Jun 15, 2006
  3. =?Utf-8?B?R2hpc3Rvcw==?=

    ObjectDataSource with list of others object in an object

    =?Utf-8?B?R2hpc3Rvcw==?=, Jun 18, 2007, in forum: ASP .Net
    Replies:
    0
    Views:
    487
    =?Utf-8?B?R2hpc3Rvcw==?=
    Jun 18, 2007
  4. Lasse Vågsæther Karlsen
    Replies:
    1
    Views:
    1,011
    Lasse Vågsæther Karlsen
    Nov 27, 2007
  5. Travis
    Replies:
    3
    Views:
    335
Loading...

Share This Page