list all items in a python class object code example

Example 1: how to get list of all instance in class python

import weakref

class MyClass:

    _instances = set()

    def __init__(self, name):
        self.name = name
        self._instances.add(weakref.ref(self))

    @classmethod
    def getinstances(cls):
        dead = set()
        for ref in cls._instances:
            obj = ref()
            if obj is not None:
                yield obj
            else:
                dead.add(ref)
        cls._instances -= dead

a = MyClass("a")
b = MyClass("b")
c = MyClass("c")

del b

for obj in MyClass.getinstances():
    print obj.name # prints 'a' and 'c'

Example 2: python list of objects

# Create a new class
class MyClass(object):
    def __init__(self, number):
        self.number = number


# Create a array to store your objects
my_objects = []

# Add 100 objects to array
for i in range(100):
    my_objects.append(MyClass(i))