[Tutor] How to find all current instances of a class?

Alan Gauld alan.gauld at yahoo.co.uk
Sun Jun 21 17:42:28 EDT 2020


On 21/06/2020 20:34, boB Stepp wrote:
> I had (perhaps) naively hoped that classes had dunder methods to list
> all current instances associated with that class, but if there is
> something that simple I have yet to find it.  Does an easy, built-in
> method exist to list all current instances of a particular class?

Further to Mats' answer, I don't know any object system that does this,
not even Smalltalk or CLOS.(The two most complete OOP systems around)
After all there can be many millions of instances - think about
strings and integers.... Tracking each instance of those would be
a lot of work.

But the "normal" way to do it if you need that facility is to
create a classmethod/attribute that holds a list of instances.
(Possibly by overriding __new__ or __init__). In fact this is
often cited as an example of a class method(as opposed to an
instance method. This is often associated with classes whose
instances are persisted in a database. So you want to know if
a particular instance is "in memory" or still in storage.
You then access the instance appropriately.

But Mat's idea of using the garbage collector is a neat trick.
I'd never have thought of that one.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list