- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I get a list of all instances of a given class in Python?
The gc or weakref module is used to get a list of all instances of a given class. First, we will install the gc module using pip −
pip install gc
To use the gc module, use the import −
import gc
Get the instances of a class using the gc module
In this example, we have created a Demo class with four instances −
ob1 = Demo() ob2 = Demo() ob3 = Demo() ob4 = Demo()
We loop through the objects in memory −
for ob in gc.get_objects():
Example
Using the isinstance(), each object is checked for an instance of the class Demo. Let us see the complete example −
import gc # Create a Class class Demo: pass # Four objects ob1 = Demo() ob2 = Demo() ob3 = Demo() ob4 = Demo() # Display all instances of a given class for ob in gc.get_objects(): if isinstance(ob, Demo): print(ob)
Output
<__main__.Demo object at 0x000001E0A407FC10> <__main__.Demo object at 0x000001E0A407EBC0> <__main__.Demo object at 0x000001E0A407EBF0> <__main__.Demo object at 0x000001E0A407EC20>
Display the count of instances of a class using the gc module
Example
In this example, we will calculate and display the count of instances −
import gc # Create a Class class Demo(object): pass # Creating 4 objects ob1 = Demo() ob2 = Demo() ob3 = Demo() ob4 = Demo() # Calculating and displaying the count of instances res = sum(1 for k in gc.get_referrers(Demo) if k.__class__ is Demo) print("Count the instances = ",res)
Output
Count the instances = 4
Display the instances of a class using weakref module
The weakref module can also be used to get the instances of a class. First, we will install the weakref module using pip −
pip install weakref
To use the gc module, use the import −
import weakref
Example
Let us now see an example −
import weakref # Create a Demo() function class Demo: instanceArr = [] def __init__(self, name=None): self.__class__.instanceArr.append(weakref.proxy(self)) self.name = name # Create 3 objects ob1 = Demo('ob1') ob2 = Demo('ob2') ob3 = Demo('ob3') # Display the Instances for i in Demo.instanceArr: print(i.name)
Output
ob1 ob2 ob3
Advertisements