Python: Are these the same object, what's going on?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MooMoo
    New Member
    • May 2008
    • 1

    Python: Are these the same object, what's going on?

    Right, heres the piece of code:

    Code:
    class Circuit:
    
        pass
    
    class Workspace:
    
        Circuits = {}
        Components = {}
    
    
    WORKSPACES = {}
    
    
    WORKSPACES["a"] = Workspace()
    WORKSPACES["b"] = Workspace()
    WORKSPACES["c"] = Workspace()
    
    #WORKSPACES["a"].Circuits["r"] = Circuit()
    
    print WORKSPACES["a"].Circuits
    print WORKSPACES["b"].Circuits
    print WORKSPACES["c"].Circuits
    Now, the output from this is:

    {'r': <__main__.Circu it instance at 0x04AD2E90>}
    {'r': <__main__.Circu it instance at 0x04AD2E90>}
    {'r': <__main__.Circu it instance at 0x04AD2E90>}

    but this isn't what I'm expecting, or what I want. TO put it best, I want the behavoius that matches this output:

    {'r': <__main__.Circu it instance at 0x04AD2E90>}
    {}
    {}


    Can anyone explain to me what's goig on here, and how I can get the behaviour I want?
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    What's going on is your class is not correct. You need to initialize your class with an __init__ function and use the self reference; otherwise all instances of this class will reference the same variables.
    [code=python]>>> class Workspace2:
    ... def __init__(self):
    ... self.Circuits = {}
    ... self.Components = {}
    ...
    >>> Workspaces2['a'] = Workspace2()
    >>> Workspaces2['b'] = Workspace2()
    >>> Workspaces2['c'] = Workspace2()
    >>> Workspaces2['a'].Circuits['r'] = Circuit()
    >>> print Workspaces2['a'].Circuits
    {'r': <__main__.Circu it instance at 0x01C894E0>}
    >>> print Workspaces2['b'].Circuits
    {}
    >>> print Workspaces2['c'].Circuits
    {}
    >>>
    [/code]

    Comment

    Working...