With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I see two options in this case:
Garbage collector
This has the disadvantage of being very slow when you have a lot of objects, but works with types over which you have no control.
Use a mixin and weakrefs
In this case, all the references get stored as a weak reference in a list. If you create and delete a lot of instances frequently, you should clean up the list of weakrefs after iteration, otherwise there’s going to be a lot of cruft.
Another problem in this case is that you have to make sure to call the base class constructor. You could also override
__new__, but only the__new__method of the first base class is used on instantiation. This also works only on types that are under your control.Edit: The method for printing all instances according to a specific format is left as an exercise, but it’s basically just a variation on the
for-loops.