Skip to content
Advertisement

How to iterate over all the instances of a class?

I know this has been asked before, but I couldn’t find an answer for my problem and all of the answers got me more confused.

So I created a class called Books, which takes as input a file location and the name of the file, and has a method called countwords which counts the words of the file.

I created a bunch of instances(are they called like this?) of this class, but I want to iterate the method CountWords on all of them. This is my code:

JavaScript

I want to write something like this:

JavaScript

and get:

JavaScript

Printing the words count of all the instances associated with the Books() class, how can I achieve this? thank you!

EDIT: I have tried different approaches but this is the one I’m using now:

  1. first one is importing weakref(don’t know what this is for).

  2. Then adding an empty list at the beginning of the class.

  3. after that use: self.__class__LISTNAME_append(weakref.proxy(self)) at the end of the def init

  4. Then you can loop through the LISTNAME.

code:

JavaScript

Advertisement

Answer

Rather than having your class keep references to all the instances that have been created, I suggest you define your data first, and then create a collection of instances from that data.

For example:

JavaScript

You can also later iterate over books to do whatever you want. Another way to do this, using a list comprehension:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement