Search code examples
pythonclassdictionaryinstanceself

How to keep track of class instances?


Toward the end of a program I'm looking to load a specific variable from all the instances of a class into a dictionary.

For example:

class Foo():
    def __init__(self):
        self.x = {}

foo1 = Foo()
foo2 = Foo()
...

Let's say the number of instances will vary and I want the x dict from each instance of Foo() loaded into a new dict. How would I do that?

The examples I've seen in SO assume one already has the list of instances.


Solution

  • One way to keep track of instances is with a class variable:

    class A(object):
        instances = []
    
        def __init__(self, foo):
            self.foo = foo
            A.instances.append(self)
    

    At the end of the program, you can create your dict like this:

    foo_vars = {id(instance): instance.foo for instance in A.instances}
    

    There is only one list:

    >>> a = A(1)
    >>> b = A(2)
    >>> A.instances
    [<__main__.A object at 0x1004d44d0>, <__main__.A object at 0x1004d4510>]
    >>> id(A.instances)
    4299683456
    >>> id(a.instances)
    4299683456    
    >>> id(b.instances)
    4299683456