how to get list of all instance in class python

Solutions on MaxInterview for how to get list of all instance in class python by the best coders in the world

showing results for - "how to get list of all instance in class python"
Carolina
18 Jul 2019
1import weakref
2
3class MyClass:
4
5    _instances = set()
6
7    def __init__(self, name):
8        self.name = name
9        self._instances.add(weakref.ref(self))
10
11    @classmethod
12    def getinstances(cls):
13        dead = set()
14        for ref in cls._instances:
15            obj = ref()
16            if obj is not None:
17                yield obj
18            else:
19                dead.add(ref)
20        cls._instances -= dead
21
22a = MyClass("a")
23b = MyClass("b")
24c = MyClass("c")
25
26del b
27
28for obj in MyClass.getinstances():
29    print obj.name # prints 'a' and 'c'
queries leading to this page
python get all instances of a classfind all existing instances of a class pythonpython list of class instancesget instances of class pythonhow to see all objects of a class in pythonpython find all objects of a classhow to see all the objects created in a class pythonpython get all instances of classhow to find list of instance in calss pythonhow to list all attributes of a python objectget all instance from class pythonpython get all instanceslist all instances of a class pythonpython list class instanceshow to see every instance of a class pythonget all instances of a class python in class methodlist all items in a python class objectpython list all methodes in classhow to add all instances of a class in a list in pythonhow to get all instances of a class in pythonhow to return list of a class in a function pythonfind all instances of a class pythonpython print all instances of a classhow can i see all the objects of a class pythonreturn list of instances of a class in pythonpython get all class instancespython list all instances of a classhow to get list of all objects of a class pythoninstance of a class in a list pythoninstance list of list pythonget list of all variables in class pythonpython return list of object from classmethodhow to get list of all instance in class pythonlist all instances pythonhow to print all instances of a class in pythonfind all instances of class pythonpython list all objects in a classpython get list of all functions in classpython find all objects of classprinting names of class instances from a list in pythonpython extend class with list shows all instancesget all instances of a class python in class method djangohow to get class instance in python from listhow to get instances of class listget all objects of a class pythonreturn list of class objects pythonget all instances of a class python how to list all objects of one class pythonhow to get all the methods of a class using instance variableshow to get a list of all instances of a class in pythonhow to get list of all instance in class python